Junior
What is the purpose of the @Bean annotation?
sobes.tech AI
Answer from AI
The @Bean annotation is used in the Spring Framework to indicate that a method produces a bean that should be registered in the application context.
Main use cases:
- Configuring third-party libraries: When it is necessary to configure objects from libraries that do not use Spring.
- Programmatic bean creation: For creating beans with complex initialization logic.
- Conditional bean creation: Using annotations such as
@ConditionalOnPropertyor@Profile, beans can be created depending on conditions.
Example of usage in a configuration class:
// Spring configuration class
@Configuration
public class AppConfig {
// creating a Service type bean
@Bean
public Service myService() {
return new ServiceImpl();
}
}