Spring Bean Annotation
Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. In this case, bean methods may reference other @Bean methods in the same class by calling them directly.
Spring Bean Example
Let’s say we have a simple class as below.
package com.journaldev.spring;
public class MyDAOBean {
@Override
public String toString() {
return "MyDAOBean" + this.hashCode();
}
}
Here is a Configuration class where we have defined a @Bean method for MyDAOBean class.
package com.journaldev.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyAppConfiguration {
@Bean
public MyDAOBean getMyDAOBean() {
return new MyDAOBean();
}
}
We can get MyDAOBean bean from Spring context using below code snippet.
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.journaldev.spring");
context.refresh();
//Getting Bean by Class
MyDAOBean myDAOBean = context.getBean(MyDAOBean.class);
Spring Bean Name
We can specify the @Bean name and use it to get them from spring context. Let’s say we have MyFileSystemBean class defined as:
package com.journaldev.spring;
public class MyFileSystemBean {
@Override
public String toString() {
return "MyFileSystemBean" + this.hashCode();
}
public void init() {
System.out.println("init method called");
}
public void destroy() {
System.out.println("destroy method called");
}
}
Now define a @Bean method in the configuration class:
@Bean(name= {"getMyFileSystemBean","MyFileSystemBean"})
public MyFileSystemBean getMyFileSystemBean() {
return new MyFileSystemBean();
}
We can get this bean from context by using the bean name.
MyFileSystemBean myFileSystemBean = (MyFileSystemBean) context.getBean("getMyFileSystemBean");
MyFileSystemBean myFileSystemBean1 = (MyFileSystemBean) context.getBean("MyFileSystemBean");
Spring @Bean initMethod and destroyMethod
We can also specify spring bean init method and destroy method. These methods are called when spring bean is being created and when the context is being closed respectively.
@Bean(name= {"getMyFileSystemBean","MyFileSystemBean"}, initMethod="init", destroyMethod="destroy")
public MyFileSystemBean getMyFileSystemBean() {
return new MyFileSystemBean();
}
You will notice that “init” method is being called when we invoke the context refresh method and “destroy” method is called when we invoke context close method.
Summary
Spring @Bean annotation is widely used in annotation-driven spring applications.