spring-boot-route (two) several ways to read configuration files

Spring Boot provides configuration files in two formats, namely propertiesand yml. The biggest feature of Spring Boot is the automated configuration. If we want to modify the default value of the automated configuration, we can specify the parameters of our own server through the configuration file.

The configuration file intensively manages the configuration information. If the configuration parameters are written into the Java code, it is very inconvenient to maintain. If the configuration file is used, we can manage and modify it uniformly. I prefer to use the ymlformat configuration file, which YAMLis a language specially used to write configuration files, usually with yml as the suffix, its structure is very clear and easier to read.

After writing the custom configuration in the configuration file, if you want to use the configuration in the java code, you need to read the configuration file at this time. There are three ways to read the configuration file. Let's introduce how to read it one by one!

The first: use @Value annotation to read

Step 1: Add the following configuration to the configuration file

config:
  name: Java旅途
  desc: spring-boot-route

Part 2: Create a new Java class to read configuration information

@RestController
public class GetValue {

    @Value("${config.name}")
    private String name;

    @Value("${config.desc}")
    private String desc;

    @GetMapping("getValue")
    public String getValue(){
        return "name="+name+";desc="+desc;
    }
}

The @Value annotation is simple to use and suitable for single parameter injection.

The second: use @ConfigurationProperties to read

Compared with @Value, @ConfigurationProperties is more suitable for reading array type parameters.

1. Get a single object

The first step: create the configuration information of the object type in the yml file

configs:
  config:
    name: Java旅途
    desc: spring-boot-route

Step 2: Create new entity mapping configuration information

@Component
@ConfigurationProperties(prefix = "configs.config")
@Data
public class Config {

    private String name;
    private String desc;
}

Step 3: Create a new class to test whether the parameters are obtained

@RestController
public class GetConfigurationProperties {

    @Autowired
    private Config config;

    @GetMapping("/getConfig")
    public String getConfig(){
        return config.getName()+";"+config.getDesc();
    }
}

2. Get a collection of objects

Step 1: Create a new array type parameter in the yml file

configs:
  config:
    - name: Java旅途
      desc: spring-boot-route
    - name: javatrip
      desc: spring-boot-yml

Step 2: Create new entity mapping configuration information

@Component
@ConfigurationProperties(prefix = "configarr")
@Data
public class Configs {

    private List<Config> config = new ArrayList<>();

    @Data
    public static class Config{

        private String name;
        private String desc;
    }
}

Step 3: Create new test class to get parameters

@RestController
public class GetConfigurationProperties {

    @Autowired
    private Configs configs;

    @GetMapping("/getConfigs")
    public String getConfigs(){

        String content = "";
        List<Configs.Config> configList = configs.getConfig();
        Map<String,Object> map = new HashMap<>();
        for (Configs.Config bean : configList){
            content += bean.getName()+";"+bean.getDesc()+",";
        }
        return content;
    }
}

In addition to the two methods described above, the configuration file information can also be read through the environment variables of the Spring Boot context. However, the above two methods can fully meet all needs, and will not be introduced here.

Think and expand

If multiple configuration files have the same configuration information, how to read specific configuration file information ?

The configuration file has priority. Generally, the priority of the yml file is higher than the properties, which will cause the configuration information of the properties to be loaded later, and the configuration information of the properties will have a higher priority when it is finally read.

The two ways to read the configuration file described above can be used in conjunction with another annotation. @PropertySource commonly uses three attributes, one is valuefor specifying the configuration file, the other is encodingfor specifying the code, and the last is factoryfor specifying Resolution factory.

Note here: @PropertySource will only load propertiesformat files by default , that is, if we specify the ymltype of file, it will not take effect. At this time, we need to rewrite the parsing factory.

First look at the default parsing factory source code:

public class DefaultPropertySourceFactory implements PropertySourceFactory {
    public DefaultPropertySourceFactory() {
    }

    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
    }
}

Custom parsing factory to implement PropertySourceFactory

public class YmlConfigFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = name != null ? name : resource.getResource().getFilename();
        if (!resource.getResource().exists()) {
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }

    private Properties loadYml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}

Step 1: Create two configuration files, test.yml and test.properties, and add the following configuration information

spring:
  value: javatrip123
  remark: javatrip123
spring:
  value: javatrip123
  remark: javatrip123

Step 2: Specify the configuration file mapping configuration file content

@Data
@Configuration
@PropertySource(value = {"classpath:test.yml"},encoding = "gbk")
@ConfigurationProperties(prefix = "spring")
public class Spring {

    private String value;
    private String remark;
}

Step 3: Create a new class for testing

@RestController
public class GetSource {

    @Autowired
    private Spring spring;

    @GetMapping("get")
    public String getSource(){
        return spring.getRemark()+";"+spring.getValue();
    }
}

This is the second article in the spring-boot-route series. The articles in this series are relatively simple. The main purpose is to help students who are new to Spring Boot have a systematic understanding. This article has been included in my github , welcome friends star!

githubhttps://github.com/binzh303/spring-boot-route

Pay attention, don't get lost

If you feel good essays, welcome attention , thumbs up , collection , your support is my creative power, thank you.

If there is a problem with the writing of the article, please don't be stingy. Please leave a message and point it out. I will check and modify it in time.

If you want to know me more deeply, you can search for " Java Journey " on WeChat to follow. Reply " 1024 " to get learning videos and exquisite e-books. Push technical articles on time at 7:30 every day, so that you are not alone on your way to work, and there are monthly book delivery activities to help you improve your hard power!

Guess you like

Origin blog.51cto.com/14820531/2539845