Spring Boot @Bean

Spring Boot @Bean

In Spring Boot @Bean 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.

Spring @Bean annotation

Spring?@Bean?annotation tells that a method produces a bean to be managed by the Spring container. It is a method-level annotation. During Java configuration (@Configuration), the method is executed and its return value is registered as a bean within a?BeanFactory.

Spring Boot @Bean example

The core Spring container 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.

src
├───main
│   ├───java
│   │   └───com
│   │       └───anjum
│   │               Application.java
│   │               AppName.java
│   └───resources
│           application.properties
│           logback.xml
└───test
    └───javal        

This is the project structure of the Spring Boot application.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0"
         xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://maven.apache.org/POM/4.0.0
         https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.anjum</groupId>
    <artifactId>springbootbean</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.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.

com/anjum/AppName.java

package com.anjum;

interface AppName {

    String getName();
}        

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

resources/application.properties

spring.main.banner-mode=off
spring.main.log-startup-info=false
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. With the?spring.main.log-startup-info?property, we can turn off the startup logging information. The?app.name?is our custom property that contains the application name.

resources/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.anjum" level="INFO"/>
</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.

com/anjum/Application.java

package com.anjum;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Autowired
    private AppName appName;

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

        return () -> appName;
    }

    @Override
    public void run(String... args) throws Exception {

        logger.info("Application name: {}", 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 () -> 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.

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

logger.info("Application name: {}", appName.getName());        

We call the bean's?getName()?method.

We run the application with?mvn -q spring-boot:run.

In this tutorial, we have created a Spring bean with the?@Bean?annotation.

要查看或添加评论,请登录

Abid Anjum的更多文章

  • Challenges in Developing Spring Boot Microservices with Spring Cloud

    Challenges in Developing Spring Boot Microservices with Spring Cloud

    Spring Boot has revolutionized the way developers build applications, particularly when it comes to microservices…

  • Microservice Challenges and Solutions

    Microservice Challenges and Solutions

    1: Microservice Dependency Failure One microservice crucial for the application’s functionality is frequently…

  • NGINX Plus

    NGINX Plus

    NGINX Plus and NGINX are the best-in-class reverse proxy and load balancing solutions used by high-traffic websites…

  • INTRODUCTION

    INTRODUCTION

    We are going to look at the features and benefits of using a Kubernetes cluster to deploy your application…

  • Clean Architecture

    Clean Architecture

    Clean architecture is a domain-centric architectural pattern that separates the business logic into two layers…

  • How to Deploy Microservices Using Serverless Architecture?

    How to Deploy Microservices Using Serverless Architecture?

    Monoliths vs. Microservices Whereas monolithic applications are built and deployed as one holistic unit…

  • Ways to Visualize Geospatial Data in a Web Browser

    Ways to Visualize Geospatial Data in a Web Browser

    Choosing a Web Visualization Library Step one. Here are a few questions to ask yourself: What kind of data do you need…

  • Java Collections Framework & Time Complexity Of Operations

    Java Collections Framework & Time Complexity Of Operations

    1. ArrayList It is used for fast random access and is mainly for storing and accessing data sequentially.

  • Improve API Performance

    Improve API Performance

    1. Caching: Leverage caching mechanisms to store frequently requested data, reducing the load on your backend and…

  • Monoliths vs Microservices

    Monoliths vs Microservices

    Monoliths vs Microservices a side by side comparison Deployability Scalability Communication Databases

社区洞察

其他会员也浏览了