Spring Boot Bean

In this tutorial, we create a simple Bean in Spring Boot framework using the @Bean annotation.

Spring is a popular Java application framework and Spring Boot is an evolution of Spring which helps create stand-alone, production-grade Spring based applications with minimal effort.

The core Spring containter creates and manages beans. In the following application, we show how to create a Spring bean with the @Bean annotation. The application is command line Spring Boot application.

$ tree
.
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── zetcode
        │           ├── Application.java
        │           └── AppName.java
        └── resources
            ├── application.properties
            └── logback.xml

This is the project structure of the Spring Boot application.

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 
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zetcode</groupId>
    <artifactId>SpringBootBean</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>    
    
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>        

    </dependencies>    

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

This is the Maven build file. The spring-boot-starter is the core starter that includes auto-configuration support, logging, and YAML. The application is packaged into a JAR file.

AppName.java
package com.zetcode;

public interface AppName {
    
    public String getName();    
}

We have a simple interface that defines a contract. It is used to create an anonymous class that returns the application name.

application.properties
spring.main.banner-mode=off
app.name=SpringBootBean

The application.properties file contains application configuration settings. There are some built-in application properties and we can create our custom ones. The spring.main.banner-mode property is a Spring built-in property; we turn off the Spring's banner. The app.name is our custom property that contains the application name.

logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.zetcode" level="ERROR"/>
</configuration>

In the logback.xml file, we configure the application logging. We set the level of logging to ERROR. This way our output is not cluttered with unnecessary information. The spring-boot-starter dependency enables logback for logging.

Application.java
package com.zetcode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private AppName appName;

    @Bean
    public AppName getAppName(@Value("${app.name}") String appName) {

        return new AppName() {

            @Override
            public String getName() {
                return appName;
            }
        };
    }

    @Override
    public void run(String... args) throws Exception {
        
        System.out.println(appName.getName());
    }
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }    
}

In the Application, we create a bean, call its method and set up the Spring Boot application. The CommandLineRunner interface indicates that a bean should run when it is contained within a SpringApplication. It can be used to create command line applications in Spring Boot.

@SpringBootApplication
public class Application implements CommandLineRunner {

The @SpringBootApplication annotation enables auto-configuration and component scanning.

@Autowired
private AppName appName;

With the @Autowired annotation we inject our AppName bean into the field.

@Bean
public AppName getAppName(@Value("${app.name}") String appName) {

    return new AppName() {

        @Override
        public String getName() {
            return appName;
        }
    };
}

Here we create the AppName bean; the bean is managed by Spring container. While the @Component annotation is used to decorate classes that are auto-detected by Spring scanning, the @Bean annotation is used to explicitly declare a bean creation.

public AppName getAppName(@Value("${app.name}") String appName) {

The @Value annotation is used to set the value of the app.name property into the appName parameter.

System.out.println(appName.getName());

We call the bean's getName() method.

$ mvn spring-boot:run -q
SpringBootBean

We run the application. The -q Maven option turns off Maven messages.

In this tutorial, we have created a Spring bean with the @Bean annotation. You might also be interested in the related tutorials: Spring Boot @Qualifier annotation, Serving static content in Spring Boot, Spring Boot DataSourceBuilder tutorial, Spring Boot iText tutorial, Spring Boot RESTFul application, Introduction to Spring web applications, Standalone Spring applications, Java tutorial.