Junior — Middle
What is the difference between @Bean and @Component annotations in Spring, and in what situations are they used?
sobes.tech AI
Answer from AI
In Spring, @Component and @Bean are used for creating and registering beans, but they differ in their application and context.
-
@Componentis a class annotation. It indicates that the class is a Spring component and should be automatically detected during component scanning. It is used for classes that Spring should instantiate and manage. -
@Beanis a method annotation within a class marked as@Configuration. A method with@Beanreturns an object that will be registered as a bean in the Spring context. It is used for creating beans when more explicit control over the creation or configuration of the object is needed.
When to use:
@Component— when you can simply annotate the class and let Spring automatically create the bean.@Bean— when you need to create a bean using a factory method, for example, for third-party classes or complex initialization.
Example:
@Component
public class MyService {
// Spring will automatically create this bean
}
@Configuration
public class AppConfig {
@Bean
public MyRepository myRepository() {
return new MyRepositoryImpl();
}
}