The @Bean annotation in Spring is used to declare a method that returns a Spring bean, which is managed by the Spring IoC (Inversion of Control) container. It is typically used in configuration classes annotated with @Configuration.
@Configuration, it indicates that the class contains bean definitions.@Configuration classes and processes their @Bean methods.@Bean method is executed, and the returned object is registered as a bean in the Spring container.@Configuration. This ensures that even if an @Bean method is called directly from within the configuration class, the proxy intercepts the call and retrieves the bean from the container instead of creating a new instance.nameDescription: Specifies one or more names for the bean. If not provided, the method name is used as the default bean name.
Type: String[]
Use Case:
Example:
@Bean(name = {"myServiceBean", "serviceAlias"})
public MyService myService() {
return new MyService();
}
myServiceBean or serviceAlias.initMethodDescription: Specifies a method to call after the bean has been initialized and dependencies injected.
Type: String
Use Case:
Example:
@Bean(initMethod = "init")
public MyService myService() {
return new MyService();
}
MyService Class:
public class MyService {
public void init() {
System.out.println("Bean is initialized");
}
}