Senior
What is the difference between the @Bean annotation and @Component?
sobes.tech AI
Answer from AI
The @Component annotation is used for automatic detection and registration of a class as a Spring bean during component scanning. This means that Spring will automatically create an instance of the class and manage its lifecycle.
The @Bean annotation is applied to methods within configuration classes (@Configuration). It indicates that the method returns an object that should be registered as a bean in the Spring context. Unlike @Component, @Bean allows explicit creation and configuration of beans, such as creating third-party objects or setting their parameters.
Example:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
@Component
public class MyComponent {
// This class will be automatically registered as a bean
}
Summary:
@Component— automatic registration of a class as a bean during scanning.@Bean— explicit creation of a bean through a method in a configuration class.