Sobes.tech
Middle

What is the difference between a component and a bean?

sobes.tech AI

Answer from AI

A component is a generalized concept of a managed Spring object (a class annotated with one of the annotations @Component, @Service, @Repository, @Controller). Spring scans the classpath, finds these classes, and creates their instances.

A bean is an instance of a component managed by the Spring IoC container. A bean has a unique name (id) in the container, a lifecycle, and can have various scopes.

Thus, a component is a "template" or "definition" (class), and a bean is an "instance" (object) created by Spring based on this template. All beans are components, but not all component classes necessarily become beans (for example, abstract classes or classes with private constructors without a factory method).

// Example of a component (class)
@Service
public class MyService {
    // ...
}
// Example of a bean (instance of MyService in the Spring context)
// Spring creates and manages this object
// You can get this bean from the context
// ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// MyService myServiceBean = context.getBean(MyService.class);
What is the difference between a component and a… - sobes.tech