Sobes.tech
Middle

Where is the @Bean annotation used?

sobes.tech AI

Answer from AI

The @Bean annotation is used on methods within configuration classes (annotated with @Configuration) to declare and register Spring beans in the application context. A method annotated with @Bean returns an object that the Spring container will instantiate, configure, and manage as a bean.

Examples of usage:

In a configuration class:

@Configuration
public class AppConfig {

    @Bean
    public MyService myService() {
        // Logic for creating a bean instance
        return new MyService();
    }

    @Bean
    public AnotherBean anotherBean(MyService myService) {
        // Dependency injection of another bean
        return new AnotherBean(myService);
    }
}

With different scopes:

@Configuration
public class SecurityConfig {

    @Bean
    @Scope("prototype") // Each request will get a new instance
    public SecurityService securityService() {
        return new SecurityService();
    }
}

With a specified bean name:

@Configuration
public class DatabaseConfig {

    @Bean(name = "myDataSource")
    public DataSource dataSource() {
        // Setup and return DataSource
        return new BasicDataSource();
    }
}
Where is the @Bean annotation used? — Java - sobes.tech