Spring @Bean Annotation Example

In this section we will learn about @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. This annotation is also a part of the spring core framework.

Create MessageService interface for message service implementations

public interface MessageService {

String getMessage();

void setMessage(String message);
}

Create implementation - SMSService class. 

public class SMSService implements MessageService{

private String message;
@Override
public String getMessage() {
return message;
}

@Override
public void setMessage(String message) {
this.message = message;
}
}

Here is a Configuration class where we have defined a @Bean method for SMSService class.

@Configuration
public class AppConfig {

@Bean
public MessageService smsService() {
return new SMSService();
}
}

We can get SMSService bean from Spring context using below code snippet.

ConfigurableApplicationContext context =
SpringApplication.run(Application.class, args);

MessageService smsService = context.
getBean(SMSService.class);
smsService.
setMessage("SMSMessageService Implementation");
System.out.println(smsService.getMessage());

context.close();


Spring Bean Name

We can specify the @Bean name and use it to get them from spring context.
Create implementation - EmailService class.

public class EmailService implements  MessageService{

private String message;

@Override
public String getMessage() {
return message;
}

@Override
public void setMessage(String message) {
this.message = message;
}
}

Now define a @Bean method in the configuration class:

@Bean(name= {"myEmailService","systemEmailService"})
public MessageService emailService() {
return new EmailService();
}

We can get this bean from context by using the bean name.

MessageService emailService = (MessageService) context.
getBean("myEmailService");
emailService.
setMessage("EmailMessageService Implementation");
System.out.println(emailService.getMessage());


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.

Create implementation - TwitterService class.

public class TwitterService implements MessageService{

private String message;
@Override
public String getMessage() {
return message;
}

@Override
public void setMessage(String message) {
this.message = message;
}

public void init() {
System.out.println("init method called");
}

public void destroy() {
System.out.println("destroy method called");
}
}

Now define a @Bean method, specify spring bean init method and destroy method in the configuration class:

@Bean(initMethod="init", destroyMethod="destroy")
public MessageService twitterService() {
return new TwitterService();
}

We can get TwitterService bean from Spring context using below code snippet.

MessageService twitterService = context.
getBean(TwitterService.class);
twitterService.
setMessage("TwitterMessageService Implementation");
System.out.println(twitterService.getMessage());


The following example creates a Spring Boot application which uses @Bean annotation.

Project Directory


pom.xml

<?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>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>spring-bean-annotation-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-bean-annotation-example</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</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-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>


MessageService.java

package com.knf.dev.demo.service;

public interface MessageService {

String getMessage();

void setMessage(String message);
}


SMSService.java

package com.knf.dev.demo.service;

public class SMSService implements MessageService{

private String message;
@Override
public String getMessage() {
return message;
}

@Override
public void setMessage(String message) {
this.message = message;
}
}


EmailService.java

package com.knf.dev.demo.service;

public class EmailService implements MessageService{

private String message;

@Override
public String getMessage() {
return message;
}

@Override
public void setMessage(String message) {
this.message = message;
}
}


TwitterService.java

package com.knf.dev.demo.service;

public class TwitterService implements MessageService{

private String message;
@Override
public String getMessage() {
return message;
}

@Override
public void setMessage(String message) {
this.message = message;
}

public void init() {
System.out.println("init method called");
}

public void destroy() {
System.out.println("destroy method called");
}
}


Configuration - AppConfig.java

package com.knf.dev.demo.config;

import com.knf.dev.demo.service.EmailService;
import com.knf.dev.demo.service.MessageService;
import com.knf.dev.demo.service.SMSService;
import com.knf.dev.demo.service.TwitterService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

@Bean
public MessageService smsService() {
return new SMSService();
}

@Bean(name= {"myEmailService","systemEmailService"})
public MessageService emailService() {
return new EmailService();
}

@Bean(initMethod="init", destroyMethod="destroy")
public MessageService twitterService() {
return new TwitterService();
}

}


Run the application - Application.java

package com.knf.dev.demo;

import com.knf.dev.demo.service.MessageService;
import com.knf.dev.demo.service.SMSService;
import com.knf.dev.demo.service.TwitterService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Application {


public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(Application.class, args);

MessageService smsService = context.
getBean(SMSService.class);
smsService.
setMessage("SMSMessageService Implementation");
System.out.println(smsService.getMessage());

MessageService emailService = (MessageService) context.
getBean("myEmailService");
emailService.
setMessage("EmailMessageService Implementation");
System.out.println(emailService.getMessage());

MessageService twitterService = context.
getBean(TwitterService.class);
twitterService.
setMessage("TwitterMessageService Implementation");
System.out.println(twitterService.getMessage());

context.close();
}
}

Application is the entry point that sets up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.

Let's run this Spring boot application from either IntelliJ IDEA IDE by right click - Run 'Application.main()'
Or you can use the below maven command to run:

mvn spring-boot:run

Console Output:
init method called
SMSMessageService Implementation
EmailMessageService Implementation
TwitterMessageService Implementation
destroy method called


Download Source Code

More related topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete