@Component
Both @Bean
are annotations used to define Spring Bean, but their functions and usage are slightly different.
-
@Component
Annotations are used to mark a class as a component in Spring, indicating that this class will be managed by the Spring container and can be used for dependency injection through the container.@Component
Annotations can@Autowired
be used together with other annotations to implement dependency injection. It works for injection of any class, including classes in third-party libraries. -
@Bean
Annotations are method-level annotations that tell the Spring container that this method will return an object that should be registered as a Bean and managed by the container.@Bean
Annotations are usually used to configure methods in classes to manually create Bean objects and add them to the Spring container.@Bean
Annotations are often@Configuration
used together with to create and configure beans in a Spring application context.
Thus, @Component
annotations are class-level annotations used to mark the class as a Spring component, and @Bean
annotations are method-level annotations used to register the object returned by the method as a Spring Bean.
Here is an @Component
example using annotations:
@Component
public class MyComponent {
// ...
}
Here is an @Bean
example using annotations:
@Configuration
public class MyConfiguration {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
In the above example, MyComponent
the class is marked as a Spring component and will be managed by the Spring container. Instead MyConfiguration
the class is marked as a @Bean
configuration class that contains a method that returns an MyBean
object and is registered as a bean by the Spring container. -