Sobes.tech
Junior — Middle

What is the purpose of the @Bean annotation when declaring methods in Spring configuration classes?

sobes.tech AI

Answer from AI

The @Bean annotation in Spring is used to explicitly declare a method that creates and returns an object managed by the Spring container as a bean. Such a method is usually located in a class annotated with @Configuration. This allows Spring to create and configure objects, manage their lifecycle, and inject dependencies.

Example:

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

Here, myService will be registered as a bean in the Spring context and available for injection into other components.