Sobes.tech
Junior — Middle

What effect does using the @Bean annotation on a method inside a class have on an instance of that class?

sobes.tech AI

Answer from AI

The @Bean annotation in the Spring Framework is used to define a method that creates and returns an object managed by the Spring container as a bean.

If a method annotated with @Bean is inside a class that itself is a Spring component (for example, marked with @Configuration), then when an instance of this class is created, Spring will call this method and register the returned object as a bean in the context.

Effects of using @Bean on a method:

  • The method is called once (if the scope is not changed), and the result is cached as a singleton bean.
  • It allows explicit configuration and creation of beans that cannot be automatically detected through scanning.
  • It enables managing dependencies and configuration through Java code.

Example:

@Configuration
public class AppConfig {

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

In this example, myService will be registered as a bean and can be injected into other components.

What effect does using the @Bean annotation on a… - sobes.tech