Several ways to read configuration file by spring boot

Time:2021-4-3

Generally speaking, there are three ways for spring boot to get files, namely @ value annotation, @ configurationproperties annotation and environment interface. These three annotations can be used with @ propertysource, which is mainly used to specify specific configuration files.

@Analysis of propertysource

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
    
    String name() default "";

    String[] value();

    boolean ignoreResourceNotFound() default false;

    String encoding() default "";

    Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
}
  • Value (): Specifies the configuration file
  • Encoding (): Specifies the encoding, because the encoding of the properties file is ios8859-1 by default, and the read is garbled
  • Factory (): Custom parsing file type, because the annotation only loads properties files by default. If you want to specify files in other formats such as YML, you need to customize the implementation.

1、 The @ value annotation reads the file

Create two new profiles config.properties and configs.properties , respectively write as follows:

zhbin.config.web - configs.name=Java journey
zhbin.config.web-configs.age=22
zhbin.config.web - configs.name=Java journey
zhbin.config.web-configs.age=18

Add a new class to read the configuration file

@Configuration
@PropertySource(value = {"classpath:config.properties"},encoding="gbk")
public class GetProperties {

    @Value("${zhbin.config.web-configs.name}")
    private String name;
    @Value("${zhbin.config.web-configs.age}")
    private String age;

    public String getConfig() {
        return name+"-----"+age;
    }
}

If we want to read the YML file, we need to rewrite the defaultpropertysourcefactory to load the YML file, and then add the annotation

@Custom factor on propertysource. The code is as follows:

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();
    }
}
@PropertySource(value = {"classpath:config.properties"},encoding="gbk",factory = YmlConfigFactory.class)

2、 Environment read file

Let’s continue to use the above two to define a class to read the configuration file

@Configuration
@PropertySource(value = {"classpath:config.properties"},encoding="gbk")
public class GetProperties {

    @Autowired
    Environment environment;

    public String getEnvConfig(){
        String name = environment.getProperty("zhbin.config.web-configs.name");
        String age = environment.getProperty("zhbin.config.web-configs.age");
        return name+"-----"+age;
    }
}

3、 @ configurationproperties read configuration file

@Configurationproperties can directly map the configuration file to an entity class, and then we can directly manipulate the entity class to obtain the data related to the configuration file.

Create a new YML file. Of course, the properties file is OK

zhbin:
  config:
    web-configs:
      Name: Java journey
      age: 20

The new entity class is used to map the configuration

@Component
@ConfigurationProperties(prefix = "zhbin.config")
@Data
public class StudentYml {
    
    //Webconfigs must correspond to the configuration file and be written as hump naming mode
    private WebConfigs webConfigs = new WebConfigs();

    @Data
    public static class WebConfigs {
        private String name;
        private String age;
    }
}
  • prefix = ” zhbin.config “Used to specify the profile prefix

If you need to get the list set, you can make the following modifications.

zhbin:
  config:
    web-configs:
      -Name: Java journey
        age: 20
      -Name: Java journey2
        age: 202
@Component
@ConfigurationProperties(prefix = "zhbin.config")
@Data
public class StudentYml {

    private List<WebConfigs> webConfigs = new ArrayList<>();

    @Data
    public static class WebConfigs {

        private String name;
        private String age;
    }
}

Experience and pit

  • The properties file uses iso8859-1 by default and cannot be modified
  • The loading order of YML file is higher than that of properties, but it will be loaded after reading the configuration information
  • @The propertysource annotation only loads the properties file by default
  • @The propertysource annotation can be used in combination with either way
  • It is recommended to use @ value for simple values and @ configurationproperties for complex objects

Recommended Today

JS generate guid method

JS generate guid method https://blog.csdn.net/Alive_tree/article/details/87942348 Globally unique identification(GUID) is an algorithm generatedBinaryCount Reg128 bitsNumber ofidentifier , GUID is mainly used in networks or systems with multiple nodes and computers. Ideally, any computational geometry computer cluster will not generate two identical guids, and the total number of guids is2^128In theory, it is difficult to make two […]