In this tutorial, we will learn everything about Spring Boot @Bean annotation with examples.
@Bean Annotation Overview
The @Bean annotation indicates that a method produces a bean to be managed by the Spring container.
The @Bean annotation is usually declared in the Configuration class to create Spring Bean definitions.
YouTube Video - @Bean Annotation
@Bean Annotation Example
In order to demonstrate the usage of @Bean annotation, let's create a couple of Java classes.
Student and Address
class Student{
private Address address;
public Student(Address address){
this.address = address;
}
public void print(){
System.out.println("Student class method called ...");
address.print();
}
}
class Address{
public void print(){
System.out.println("Address class method called ...");
}
}
AppConfig Class
Next, let's create a Java configuration class annotated with @Configuration annotation. Within this class, let's create bean definitions using @Bean annotation.
@Configuration
class AppConfig{
@Bean
public Address address(){
return new Address();
}
@Bean
public Student student(){
return new Student(address());
}
}
Bean Names
By default, the bean name is the same as the method name. We can specify the bean names using @Bean(name = “beanName”).
For example:
@Bean(name = "addressBean")
public Address address(){
return new Address();
}
@Bean(name = "studentBean")
public Student student(){
return new Student(address());
}
Define Mulitple Bean Names
We can also specify multiple names for a single Spring bean.
For example:
@Bean(name = {"studentBean", "studentDemo", "studentComponent"})
public Student student(){
return new Student(address());
}
Next, we can retrieve the student Spring bean object using any of these bean names. For example:
Student student = (Student) applicationContext.getBean("studentBean");
Or
Student student = (Student) applicationContext.getBean("studentDemo");
Or
Student student = (Student) applicationContext.getBean("studentComponent");
@Bean initMethod and destroyMethod attributes
@Bean annotation provides initMethod and destroyMethod attributes to perform certain actions after bean initialization or before bean destruction by a container.
For example, the Student Spring bean has initMethod and destroyMethod attributes:
@Configuration
class AppConfig{
@Bean(name = "addressBean")
public Address address(){
return new Address();
}
@Bean(name = "studentBean", initMethod = "init", destroyMethod = "destroy")
public Student student(){
return new Student(address());
}
}
Next, create init() and destroy() methods in Student class:class Student{
private Address address;
public Student(Address address){
this.address = address;
}
public void print(){
System.out.println("Student class method called ...");
address.print();
}
public void init(){
System.out.println("Intialization logic");
}
public void destroy(){
System.out.println("Destruction logic");
}
}
Testing
Run the below code to test all the @Bean annotation use cases:
public class BeanAnnotationDemo {
public static void main(String[] args) {
try(var applicationContext = new AnnotationConfigApplicationContext(AppConfig.class)){
//Student student = applicationContext.getBean(Student.class);
Student student = (Student) applicationContext.getBean("studentBean");
String[] beanNames = applicationContext.getBeanDefinitionNames();
for (String bean: beanNames){
System.out.println(bean);
}
student.print();
}
}
}
Complete Code
Here is the complete code for your reference:
package com.spring.core.beans;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
class Student{
private Address address;
public Student(Address address){
this.address = address;
}
public void print(){
System.out.println("Student class method called ...");
address.print();
}
public void init(){
System.out.println("Intialization logic");
}
public void destroy(){
System.out.println("Destruction logic");
}
}
class Address{
public void print(){
System.out.println("Address class method called ...");
}
}
@Configuration
class AppConfig{
@Bean(name = "addressBean")
public Address address(){
return new Address();
}
@Bean(name = "studentBean", initMethod = "init", destroyMethod = "destroy")
public Student student(){
return new Student(address());
}
}
public class BeanAnnotationDemo {
public static void main(String[] args) {
try(var applicationContext = new AnnotationConfigApplicationContext(AppConfig.class)){
//Student student = applicationContext.getBean(Student.class);
Student student = (Student) applicationContext.getBean("studentBean");
String[] beanNames = applicationContext.getBeanDefinitionNames();
for (String bean: beanNames){
System.out.println(bean);
}
student.print();
}
}
}
Conclusion
In this tutorial, we have seen how to use @Bean annotation to create and manage Spring bean by Spring container. We have also seen how to use initMethod and destroyMethod attributes of @Bean annotation.
Related Spring and Spring Boot Annotations
- Spring Boot @Bean Annotation Example
- Spring @Qualifier Annotation Example
- Spring @Autowired Annotation with Example
- Spring @Bean Annotation with Example
- Spring @Configuration Annotation with Example
- Spring @PropertySource Annotation with Example
- Spring @Import Annotation with Example
- Spring @ImportResource Annotation Example
- Spring - @Lazy Annotation Example
- Spring - @Primary Annotation Example
- Spring @PostConstruct and @PreDestroy Example
- Spring @Repository Annotation
- Spring @Service Annotation
- The Spring @Controller and @RestController Annotations
- Spring Boot @Component, @Controller, @Repository and @Service
- Spring @Scope annotation with Prototype Scope Example
- Spring @Scope annotation with Singleton Scope Example
- Spring Boot @PathVariable
- Spring Boot @ResponseBody
- Spring @RequestBody - Binding Method Parameters to Request Body
- Spring Boot @ResponseStatus Annotation
- Spring Boot - Creating Asynchronous Methods using @Async Annotation
- @SpringBootTest Spring Boot Example
- @SpringBootTest vs @WebMvcTest
- @DataJpaTest Spring Boot Example
- Spring @PostConstruct and @PreDestroy Example
- Spring @GetMapping, @PostMapping, @PutMapping, @DeleteMapping and @PatchMapping
- Spring Boot @EnableAutoConfiguration Annotation with Example
- Spring Boot @SpringBootApplication Annotation with Example
Comments
Post a Comment
Leave Comment