Junior
What is the value of the @Bean annotation in Spring?
sobes.tech AI
Answer from AI
The @Bean annotation in Spring is used to declare a method within a class annotated with @Configuration or @Component (and its derivatives), which will create, configure, and initialize a new object managed by the Spring IoC container.
Main benefits:
- Explicit bean declaration: Allows explicitly specifying which object should be included in the Spring application context and how to obtain it.
- Bean configuration: Provides the ability to finely tune the creation and configuration of the object, performing necessary logic before returning it.
- External dependencies: Convenient for integrating external libraries or components that cannot be directly annotated, or when their creation requires complex logic.
- Conditional creation: Allows creating beans conditionally, for example, based on environment properties or the presence of other beans.
- Lifecycle management: Enables defining initialization (
@Bean(initMethod = "...")) and destruction (@Bean(destroyMethod = "...")) methods for the bean.
Example usage:
@Configuration
public class AppConfig {
@Bean
public MyService myService() // Method that returns a MyService object
{
// Complex logic for creating and configuring MyService
MyService service = new MyService();
service.setConfig("someValue");
return service; // Returns the object that will become a Spring bean
}
@Bean
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public FeatureService featureService() {
return new FeatureService();
}
}