Sobes.tech
Junior — Middle

What is the role of the Bean annotation in the Spring framework and how is it used in component creation?

sobes.tech AI

Answer from AI

In Spring, the @Bean annotation is used for explicit component (bean) definition within a configuration class. It informs Spring that the method annotated with this annotation returns an object that should be registered in the application context as a Spring Bean.

This is useful when you need to create and configure an object manually, rather than relying on automatic component scanning (@Component).

Example of usage:

@Configuration
public class AppConfig {

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

Here, the myService() method creates and returns an instance of MyServiceImpl, which Spring registers as a bean named myService. This bean can then be injected into other components via @Autowired.

Thus, @Bean allows flexible management of component creation and configuration in Spring.

What is the role of the Bean annotation in the Spring… - sobes.tech