Junior
What is the purpose of the @Bean annotation in Spring?
sobes.tech AI
Answer from AI
The @Bean annotation is used in the Spring Framework to explicitly declare a separate bean (component) that should be created and managed by the Spring IoC container.
Main reasons for its use:
- Integration of third-party libraries: Allows easy integration of objects created by third-party libraries that are not annotated with
@Component,@Service,@Repository, etc. - Object configuration: Provides full control over the object creation process, allowing dependencies to be passed to it and its properties to be configured in Java configuration.
- Multiple instances of the same class: Allows creating multiple beans of the same class with different configurations.
- Conditional bean creation: In combination with
@Conditional, beans can be created depending on certain conditions. - Clear separation of configuration and business logic: Application configuration is concentrated in classes annotated with
@Configuration, while business logic resides in classes with@Component.
Example of usage in a @Configuration class:
// MyConfiguration.java
package com.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfiguration {
@Bean
public MyService myService() {
// Creating and configuring the Service object
return new MyService();
}
@Bean
public DataSource dataSource() {
// Creating and configuring the data source
// This can be an object from a third-party library
return new com.example.DataSourceImpl();
}
}