Spring boot @Bean annotation with example





Hey guys in this post we will discuss everything you need to know about Spring boot @Bean annotation with example.

Overview


@Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically. It decouples the declaration of the bean from the class definition and lets you create and configure beans exactly how you choose.

@Bean is a method-level annotation. We generally use it to configure beans in Java code (if you are not using XML configuration) and then call it from a class using the ApplicationContext.getBean() method.

@Configuration
class MyConfiguration{
    @Bean
    public User getUser() {
        return new User();
    }
}

class User{
}    
        
// Getting Bean 
User user = applicationContext.getBean("getUser");

The @Bean annotation returns an object that spring should register as a bean in the application context. The body of the method bears the logic responsible for creating the instance.

Watch the video


Example on @Bean annotation


The best way to understand @Bean annotation is by looking at the complete example by creating a spring application.

Create Spring boot project


There are different ways to create a spring boot project, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>beanannotation</artifactId>
	<version>v1</version>
	<name>beanannotation</name>
	<description>Spring boot bean annotation</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container.




spring-boot-devtools dependency for automatic reloads or live reload of applications.

Create an entity


Create User.java inside in.bushansirgur.springboot.entity package and add the following content

package in.bushansirgur.springboot.entity;

public class User {
	
	private String name;
	
	public User(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "User [name=" + name + "]";
	}
	
}

Create a service


Create UserService.java inside in.bushansirgur.springboot.service package and add the following content

package in.bushansirgur.springboot.service;

import java.util.ArrayList;
import java.util.List;

import in.bushansirgur.springboot.entity.User;

public class UserService {
	
	private static List list = new ArrayList<>(); 
	
	static {
		User u = new User("User 1");
		list.add(u);
		
		u = new User("User 2");
		list.add(u);
		
		u = new User("User 3");
		list.add(u);
	}
	
	public List getList () {
		return list;
	}
}

Create a configuration class


Create MyConfig.java inside in.bushansirgur.springboot.config package and add the following content

package in.bushansirgur.springboot.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import in.bushansirgur.springboot.service.UserService;

@Configuration
public class MyConfig {
	
	@Bean(name={"myBean", "mySecondBean"})
    public UserService getUser() {
        return new UserService();
    }
}

@Configuration annotation tells Spring container that there are one or more beans that need to be dealt with on runtime.

@Bean takes optional element name which is an array, we can multiple alias name with comma separated.

Create the main class


Open BeanannotationApplication.java and the following content

package in.bushansirgur.springboot;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import in.bushansirgur.springboot.service.UserService;


@SpringBootApplication
public class BeanannotationApplication{

	public static void main(String[] args) {
		ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanannotationApplication.class);
		//By its type
		UserService user = ctx.getBean(UserService.class);
		System.out.println("Printing user:"+user.getList());
	}
}

Get Bean by its alias name


We can also get the bean by its alias name. getBean() accepts the alias name, and we need to typecast it to the bean type.

package in.bushansirgur.springboot;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import in.bushansirgur.springboot.service.UserService;


@SpringBootApplication
public class BeanannotationApplication{

	public static void main(String[] args) {
		ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanannotationApplication.class);
		//By its alias name
		UserService user = (UserService)ctx.getBean("myBean");
		System.out.println("Printing user:"+user.getList());
	}
}

run the app


mvn spring-boot:run

Output:

Printing user:[User [name=User 1], User [name=User 2], User [name=User 3]]




About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *