Use @ ConfigurationProperties for configuration binding in SpringBoot

Use Java to read The contents of the properties file are and encapsulated into JavaBean s

  1. New Maven project: demo1.
  2. Modify POM XML, add 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo1</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>
    </dependencies>
</project>
  1. New class com example. boot. bean. Car.
package com.example.boot.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Car {
    private String brand;
    private Integer price;
}
  1. Create a new configuration file application. Under resources properties.
brand=BYD
price=100000
  1. New controller com example. boot. controller. DemoController.
package com.example.boot.controller;

import com.example.boot.bean.Car;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Controller
public class DemoControlller {
    @RequestMapping("/car")
    @ResponseBody
    public Car car() {
        Car car = new Car();
        try {
            car = getProperties();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }finally {
            return car;
        }
    }
    public Car getProperties() throws IOException, InvocationTargetException, IllegalAccessException {
        Car car = new Car();
        Properties pps = new Properties();
        pps.load(new FileInputStream("src/main/resources/application.properties"));
        Map<String,String> map = new HashMap<>();
        Enumeration enumeration = pps.propertyNames();
        while(enumeration.hasMoreElements()){
            String strKey = (String) enumeration.nextElement();
            String strValue = pps.getProperty(strKey);
            map.put(strKey,strValue);
            System.out.println(strKey + "=" + strValue);
        }
        BeanUtils.populate(car,map);
        return car;
    }
}

Here, Java is used to read application Properties file and encapsulate it into JavaBean s through BeanUtils (the dependency commons bean utils is added to the pom configuration file).

  1. Create a new main startup class com example. boot. MainApplication.
package com.example.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args){
        SpringApplication.run(MainApplication.class,args);
    }
}
  1. Start the application and access the interface localhost:8080/car.

Use SpringBoot's @ ConfigurationProperties for configuration binding

In the Spring project, there may be a large number of parameters configured in the application Properties or application In YML, we used to read the contents of the configuration file through Java to obtain these parameters. See the above example, which is trivial and complicated, and the @ ConfigurationProperties annotation provided by SpringBoot can help us easily obtain them. Don't believe it? Look down.

@ConfigurationProperties
  1. Modify com example. boot. bean. Car.
package com.example.boot.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@NoArgsConstructor
@AllArgsConstructor
@Data
@Component
@ConfigurationProperties
public class Car {
    private String brand;
    private Integer price;
}

Pay attention to two points.
First point: @ Component, mark the Car as a normal Component and add it to the SpringBoot container. Note that only components added to the SpringBoot container can use the powerful functions provided by SpringBoot.

@Component, marked as normal component
@Controller, labeled as control layer component
@Service, marked as service layer component
@Repository, labeled as a persistence layer component

The second point: @ ConfigurationProperties, you can automatically inject configuration values for properties.
application. brand=BYD configured in properties, and BYD automatically becomes the default value of brand property of Car; application. The price=10000001000000 configured in properties automatically becomes the default value of the price property of Car.

  1. Modify com example. boot. controller. DemoController.
package com.example.boot.controller;

import com.example.boot.bean.Car;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DemoControlller {
    @Autowired
    private Car car;
    
    @RequestMapping("/car")
    @ResponseBody
    public Car car() {
        return car;
    }
}
  1. Start the application and access the interface localhost:8080/car.



As shown in the figure above, the prefix property must be specified when using @ ConfigurationProperties (however, we didn't specify it just now, and there was no error when running. Specifying the prefix property is a best practice). Let's take a look at the best practice.

@ConfigurationProperties(prefix = "mycar")
  1. Modify application Properties, prefixed with mycar.
mycar.brand=BYD
mycar.price=100000
  1. Modify com example. boot. bean. Car,@ConfigurationProperties(prefix = "mycar").
package com.example.boot.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@NoArgsConstructor
@AllArgsConstructor
@Data
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;
}
  1. Restart the application, visit localhost:8080/car, and get the result successfully.

As mentioned above, you need to add the Car to the SpringBoot container to configure the binding using the @ ConfigurationProperties annotation of SpringBoot.
The @ Component+@ConfigurationProperties solution has just been introduced.
Here is another solution: @ EnableConfigurationProperties+@ConfigurationProperties.

  1. New com example. boot. config. MyConfig.
package com.example.boot.config;

import com.example.boot.bean.Car;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(Car.class)
public class MyConfig {
}

@EnableConfigurationProperties(Car.class) has two functions: one is to enable the property configuration function or configure the binding function; The other is to register Car as a component in the SpringBoot container.

  1. Restart the application, access the interface localhost:8080/car, and get the expected results.

Keywords: Java Spring Spring Boot SpringBoot2

Added by byronwells on Wed, 22 Dec 2021 13:21:39 +0200