Three methods for SpringBoot to read configuration files

analysis

SpringBoot provides three ways to read the content of the application.properties configuration file of the project. The methods are: Environment class @Value Notes and @ConfigurationProperties Notes.

What you must know: the following three ways can get the information of the configuration file. Don't worry about the good or bad of that way. As long as we can solve the problem.

01. Environment get attribute value

Environment is a class used to read the environment variables of application runtime. You can read application.properties and system environment variables, command line input parameters, system properties, etc. through key value, as follows:

The definition in the application.yml file is as follows:

# Property configuration class
server:
  port: 8082

spring:
  main:
    banner-mode: console

# custom
alipay:
  pay:
    appid: 123456
    notify: http://www.xxx.com

Define the read classes as follows:

package com.kuangstudy.web.properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Description:
 * Author: yandi Administrator
 * Version: 1.0
 * Create Date Time: 2021/12/11 21:25.
 * Update Date Time:
 *
 * @see
 */
@RestController
public class ReadPropertiesEnvironment {

    @Autowired
    private Environment environment;


    @GetMapping("/read/file")
    public Map<String,Object> readInfo(){
        Map<String,Object> map = new HashMap<>();
        map.put("port",environment.getProperty("server.port"));
        map.put("appid",environment.getProperty("alipay.pay.appid"));
        map.put("notify",environment.getProperty("alipay.pay.notify"));
        map.put("javaversion",environment.getProperty("java.version"));
        map.put("javahome",environment.getProperty("JAVA_HOME"));
        map.put("mavenhome",environment.getProperty("MAVEN_HOME"));
        return  map;
    }

    public static void main(String[] args) {
        Properties properties = System.getProperties();
        Set<String> strings = properties.stringPropertyNames();
        for (String string : strings) {
            System.out.println(string+"===>"+properties.get(string));
        }

    }

}

Access in browser

http://localhost:8082/read/file

02. Read configuration file attributes -@Value

use @Value Annotation reads the contents of the configuration file, as follows:

package com.kuangstudy.web.properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Description:
 * Author: yandi Administrator
 * Version: 1.0
 * Create Date Time: 2021/12/11 21:25.
 * Update Date Time:
 *
 * @see
 */
@RestController
public class ReadPropertiesValue {

    @Value("${server.port}")
    private Integer port;
    @Value("${alipay.pay.appid}")
    private String appid;
    @Value("${alipay.pay.notify}")
    private String notify;
    @Value("${java.version}")
    private String javaVersion;
    @Value("${JAVA_HOME}")
    private String javaHome;
    @Value("${MAVEN_HOME}")
    private String mavenHome;


    @GetMapping("/read/value")
    public Map<String, Object> readInfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("port", port);
        map.put("appid", appid);
        map.put("notify", notify);
        map.put("javaversion", javaVersion);
        map.put("javahome", javaHome);
        map.put("mavenhome", mavenHome);
        return map;
    }

}

The browser is as follows:

Conclusion: Actually @Value The bottom layer is Environment.java

03. Read configuration file properties - @ConfigurationProperties

use @ConfigurationProperties First, establish the mapping relationship between the configuration file and the object, and then use it in the controller method @Autowired Annotations inject objects. The details are as follows:

01. Customize attributes in application.yml

# Custom attributes
ksd:
  alipay:
    appid: 2021003100625328
    mkey: MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC9kGK4VMbYm
    ckey: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx5i5LhEtDZw6Q6mUxkC5f6sAvZm9OncAkRXwfoBdDeKk
    callback: https://www.txnh.net/api/alipay/returnUrl
    charset: UTF-8

02. Define attribute configuration class and attribute class

Attribute configuration classes are as follows:

package com.kuangstudy.properties.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Description:
 * Author: yandi Administrator
 * Version: 1.0
 * Create Date Time: 2021/12/14 20:53.
 * Update Date Time:
 *
 * @see
 */
@ConfigurationProperties(prefix = "ksd.alipay")//This annotation is used to find classes
@Data
public class AlipayProperties {
    private String appid;
    private String mkey;
    private String ckey;
    private String callback;
    private String charset ="UTF-8";
}

The attribute configuration class must be registered in the configuration class, as follows:

package com.kuangstudy.properties.config;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

/**
 * Description:
 * Author: yandi Administrator
 * Version: 1.0
 * Create Date Time: 2021/12/14 20:53.
 * Update Date Time:
 *
 * @see
 */
// Register with configuration class: attribute configuration class
@EnableConfigurationProperties(AlipayProperties.class)
@SpringBootConfiguration
public class AlipayConfiguration {

}

03. Use of attribute configuration class

package com.kuangstudy.properties;

import com.kuangstudy.properties.config.AlipayProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Description:
 * Author: yandi Administrator
 * Version: 1.0
 * Create Date Time: 2021/12/14 20:36.
 * Update Date Time:
 *
 * @see
 */
@RestController
@Slf4j
public class AlipayController2 {

    @Autowired
    private AlipayProperties alipayProperties;

    @GetMapping("/alipay2")
    public String alipay2() {
        log.info("You pay yes:{}", alipayProperties);
        return "success";
    }

}

04. Automatic prompt and warning about custom attributes

The solution steps are as follows:

01. Automatically prompt procossor since pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
</dependency>

02. The application.yml file opened by idea must be closed

03. Then open application.yml again

The automatic prompt will appear and the warning will disappear. Then enter ksd. and the automatic prompt will appear

summary
1. Environment @Value does not have the characteristics of object-oriented. If there are too many attributes, it is not convenient to manage and control. If there are too many attributes, it will appear disorderly. And there is no automatic prompt function.
2. @ConfigurationProperties is an object-oriented mechanism that can prompt automatically.
So the underlying springboto uses @ConfigurationProperties
3. Of course, in the development, you can get the same effect with that, and you can choose the best way according to the business.

First of all, I would like to introduce myself. I graduated from Jiaotong University in 13 years. I once worked in a small company, went to large factories such as Huawei OPPO, and joined Alibaba in 18 years, until now. I know that most junior and intermediate Java engineers who want to improve their skills often need to explore and grow by themselves or sign up for classes, but there is a lot of pressure on training institutions to pay nearly 10000 yuan in tuition fees. The self-study efficiency of their own fragmentation is very low and long, and it is easy to encounter the ceiling technology to stop. Therefore, I collected a "full set of learning materials for java development" and gave it to you. The original intention is also very simple. I hope to help friends who want to learn by themselves and don't know where to start, and reduce everyone's burden at the same time. Add the business card below to get a full set of learning materials

Tags: Back-end Front-end Android Interview

Posted by ArneR on Fri, 05 Aug 2022 02:44:06 +0930