spring boot study notes (c) of configuration

I. Overview

     According to business needs, we tend to configure the key-value configuration items we need in a different place in Spring boot, there are different places profiles scenario is as follows:

(1) there is a default or application.properties application.yaml, and these files can be placed in different parts of the project, such as: the project root directory, the project root directory / config, under src / main / resources, src / main / resources under / config, reference works, and even these two files exist;

(2) for (1) or application.properties application.yaml, and there are arranged in different environments;

(3) The profile of the key may be configured Spring boot configuration, such as: server.port, spring.datasource * configuration, etc., may be disposed while our custom key;.

(4) In order to prevent application.properties become bloated, we will be required to configure key projects placed in a custom profile, and the profile can be to (1) be placed in any position on the same;

II: Features

1, custom configuration

In application.xml or application.yaml (1) store custom configuration

     Use @ ConfigurationProperties annotations or notes directly injected directly @Value attribute value

     The use of the prefix @ ConfigurationProperties incoming annotation property may not be annotated, but requires a corresponding setter method requires otherwise, the value is not set to go;

     The method can be used without @Value setter method, which is obtained by setting the value otherwise go;

Examples are as follows:

package com.example.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 自定义配置属性注入(配置项存储在 application.properties 中)
 *
 * @author sandy
 *
 */
@Component
@ConfigurationProperties(prefix = "hello")
public class CoustomPropertiesInjectV1 {
    private String username;
    @Value("${hello.test.username}")
    private String testUsername;
    
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getTestUsername() {
        return testUsername;
    }
    public void setTestUsername(String testUsername) {
        this.testUsername = testUsername;
    }
}

 

@GetMapping("/configurationProperties")
    public CoustomPropertiesInjectV1 findPropertiesInjectV1(){
        return propertiesInjectV1;
    }

 

Description:

  • In the presence of the project src / main / resources applicaton.properties file exists hello prefix entry in the configuration file, mainly:
# Custom configuration items
 hello.username = sandy_classpath_applicaiton_properties 
hello.test.username = test_classpath_applicaiton_properties

 

  • For hello.username in @ Configuration Properties (direct injection quantities, injection with automatic prefix different configuration items) it has been configured prefix represents the prefix configured as "hello" are injected into the current class attribute, but only the prefix .XXX the same name as the current injected into the class attribute XXX;
  • In use @ Configuration Properties , the need to increase the Maven dependency:
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
     <optional>true</optional>
</dependency>

 

  •      The understanding of the above hello.test.username injected through the prefix is not coming, because the property class name is not contained, therefore. "" Test.username not be used as the attribute name, this time can be used for injection @Value;

According to the above description, custom configuration injection with two annotations can be used: @ Configuration Properties or @Value;

(2) custom configuration entry exists in the custom configuration file (the file name is not applicaiton)

    a) add comments on the class: @PropertySource, specified load custom profiles (only for properties files)

Package com.example.demo.config; 

Import org.springframework.beans.factory.annotation.Value;
 Import org.springframework.boot.context.properties.ConfigurationProperties;
 Import org.springframework.context.annotation.PropertySource;
 Import org.springframework .stereotype.Component; 

/ ** 
 * custom configuration attributes injection (CI stored in the cutom.properties) 
 * <Li> Although the configuration of @PropertySource, and other files specified loading configuration items, but in fact will go application.properties loaded configuration <br> 
 * when the key configuration items consistent with applicaiton.properties class, attribute values loaded in the same name as key applicaiton.propeties; 
 * </ Li> 
 * <Li> custom profile when the class context, value can be added in the classpath specified in the class file path, or without this, also the default class Road King </ li> 
 * <Li> load file system, not in the class custom profile under path, use the file, with the default load path from the project </ li>
 * <Li> @PropertySource value attribute can specify a plurality of local configuration files, if the file name exists in a different key, the latter over the former </ Li> 
 * @author Sandy 
 * 
 * / 
@PropertySource (value = { "CLASSPATH : custom.properties "," File: config / custom-config-dir.properties " }) 
@Component 
@ConfigurationProperties (prefix =" Hello " )
 public  class CoustomPropertiesInjectV2 {
     Private String usernameV2; 
    @Value ( " {$ hello.test. } usernameV2 " )
     Private String testUsernameV2; 
    
    / ** * file with the same name exists application.properties key CI ** * / 
    Private String username;
    @Value("${hello.test.username}")
    private String testUsername;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getTestUsername() {
        return testUsername;
    }
    public void setTestUsername(String testUsername) {
        this.testUsername = testUsername;
    }
    public String getUsernameV2() {
        return usernameV2;
    }
    public void setUsernameV2(String usernameV2) {
        this.usernameV2 = usernameV2;
    }
    public String getTestUsernameV2() {
        return testUsernameV2;
    }
    public void setTestUsernameV2(String testUsernameV2) {
        this.testUsernameV2 = testUsernameV2;
    }
}
@GetMapping("/configurationProperties/V2")
    public CoustomPropertiesInjectV2 findPropertiesInjectV2(){
        return propertiesInjectV2;
    }

 

  Configuration file in the project directory /config/custom-config-dir.properties, classpath /custom.properties

  Project directory /config/custom-config-dir.properties document reads as follows:

hello.usernameV2=sandy_root_config_dir_custom_propeties
hello.test.usernameV2=test_root_config_dir_custom_propeties

hello.username=sandy_root_config_dir_custom_propeties
hello.test.username=test_root_config_dir_custom_propeties

 

Classpath /custom.properties follows:

hello.usernameV2=sandy_classpath_custom_propeties
hello.test.usernameV2=test_classpath_custom_propeties

hello.username=sandy_classpath_custom_propeties
hello.test.username=test_classpath_custom_propeties

 

Visit the restful interfaces, returns the contents as follows:

{
    "usernameV2": "sandy_root_config_dir_custom_propeties",
    "testUsernameV2": "test_root_config_dir_custom_propeties",
    "username": "sandy_classpath_applicaiton_properties",
    "testUsername": "test_classpath_applicaiton_properties"
}

 

In summary the following conclusions:

  • Specify the load profile by propertiesSource label, did not say if you want to load application.properties file, the default file will be loaded application.properties;
  • Custom configuration file of the same name exists application.properties key, Key places with the same name in whichever application.properties;
  • propertiesSource value attribute specifies a plurality of external files, files with the same name exist in different key, over the former after loading the key value of the same name;

 b) yml customization file for the file, loading patterns used @bean

   Add the following classes on the basis of the foregoing

Package com.example.demo.config.dto; 

Import org.springframework.beans.factory.annotation.Value;
 Import org.springframework.stereotype.Component; 

@Component 
public  class CoustomYamlInjectV1 {
     Private String usernameV2; 
    @Value ( "{$ YML } .test.usernameV2 " ) // the final value is the project directory /config/custom-config-dir.yml file
     Private String testUsernameV2; 
    
    / ** * application.properties file with the same name exists key configuration items ** * / 
    Private String username; 
    @Value ( "hello.test.username $ {}" )
     Private String testUsername;   //最终值为 application.properties中的值
    @Value("${hello.test.usernameV2}")  //最终值为 config/config/custom-config-dir.properties 文件中的值
    private String helloTestUsernameV2;
    
    public String getHelloTestUsernameV2() {
        return helloTestUsernameV2;
    }
    public void setHelloTestUsernameV2(String helloTestUsernameV2) {
        this.helloTestUsernameV2 = helloTestUsernameV2;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getTestUsername() {
        return testUsername;
    }
    public void setTestUsername(String testUsername) {
        this.testUsername = testUsername;
    }
    public String getUsernameV2() {
        return usernameV2;
    }
    public void setUsernameV2(String usernameV2) {
        this.usernameV2 = usernameV2;
    }
    public String getTestUsernameV2() {
        return testUsernameV2;
    }
    public  void setTestUsernameV2 (String testUsernameV2) {
         this .testUsernameV2 = testUsernameV2; 
    } 
}

 

package com.example.demo.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;

/**
 * 测试加载自定义 yaml文件
 * @author sandy
 *
 */
@Configuration
public class CoustomYamlConfigV1 {
    @Bean
    public static PropertySourcesPlaceholderConfigurer loadProperties() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        //yaml.setResources(new FileSystemResource("classpath:config/user.yml"));//File路径引入
        yaml.setResources(new ClassPathResource("coustom.yml"),new FileSystemResource("config/custom-config-dir.yml"));//class路径引入
        configurer.setProperties(yaml.getObject());
        returnset; 
    } 
}

 

@GetMapping("/yml")
    public CoustomYamlInjectV1 findYamlInject(){
        return coustomYamlInjectV1;
    }

 

yml configuration file as follows:

 src/main/resources/custom.yml

yml: 
   usernameV2: sandy_classpath_custom_yml
   test:
      usernameV2: test_classpath_custom_yml
      
hello: 
   usernameV2: sandy_classpath_custom_yml
   username: sandy_classpath_custom_yml
   test: 
      usernameV2: hello_test_classpath_custom_yml
      username: test_classpath_custom_yml  

 

Under the project directory /config/custom-config-dir.yml

yml: 
   usernameV2: sandy_root_config_dir_custom_yml
   test:
      usernameV2: test_root_config_dir_custom_yml
      
hello: 
   usernameV2: sandy_root_config_dir_custom_yml
   username: sandy_root_config_dir_custom_yml
   test: 
      usernameV2: hello_root_config_dir_custom_yml
      username: test_root_config_dir_custom_yml  

 

The final restful Interface returns:

{
    "usernameV2": null,
    "testUsernameV2": "test_root_config_dir_custom_yml",
    "username": null,
    "testUsername": "test_classpath_applicaiton_properties",
    "helloTestUsernameV2": "test_root_config_dir_custom_propeties"
}

 

2, coexistence and application.yml application.properties

      (1) When the presence of these two files is only src / main / resources

package com.example.demo.config.dto;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ApplicationPropertiesV1 {
    @Value("${day.username}")
    private String helloUsername;
    @Value("${day.test.username}")
    private String helloTestUsername;

    public String getHelloUsername() {
        return helloUsername;
    }

    public void setHelloUsername(String helloUsername) {
        this.helloUsername = helloUsername;
    }

    public String getHelloTestUsername() {
        return helloTestUsername;
    }

    public void setHelloTestUsername(String helloTestUsername) {
        this.helloTestUsername = helloTestUsername;
    }

}

 

@GetMapping("/application")
    public ApplicationPropertiesV1 findApplicationInject(){
        return applicationPropertiesV1;
    }

 

src/main/resources/applicaiton.properties

day.username=day_sandy_classpath_applicaiton_properties
day.test.username=day_test_classpath_applicaiton_properties

 

src/main/resources/applicaiton.yml

day: 
   username: day_sandy_classpath_applicaiton_yml
   test: 
      username: test_classpath_applicaiton_yml

 

restful result of the call interfaces

{
    "helloUsername": "day_sandy_classpath_applicaiton_yml",
    "helloTestUsername": "test_classpath_applicaiton_yml"
}

 

Description:

     In the same class path, properties higher priority than yml, the same name as the former shall control key;

   (2) application global configuration files in different directories:

SpringBoot profile can be placed in the various paths, arranged in different paths different priority.
Contents may be placed (highest to lowest priority)

    File: ./ (config directory path to the current project) config /;
    File: ./ (current path item);
    CLASSPATH: / config / (classpath directory config);
    . classpath: / (classpath config)

priority in the end, higher priority configuration overwrites the low priority configured by high; occur when the same name as the key, the value of the high-priority directory profile prevail ;
SpringBoot will be loaded from the four positions of all profiles and complementary configuration;

Link explained with reference to (2): https: //blog.csdn.net/IT_faquir/article/details/80869578

(3) application.properties dependencies exist in

    This project dependency application.properties higher priority than the profile of the package, only loaded when the loading profile of the present project, depending not load package.

 

Three: summary

Way configurations are the following:

  • Configuration file from the beginning applicaiton (properties or end yml);

             A) properties yml disposed above configuration, two files are loaded, but the value of the same name key properties of the subject;

             b) dependencies there are also application configuration file, the same name of the configuration file will only be loaded one, this project exists, load the configuration file in this project, or load-dependent configuration file in the package;

             c) application profiles placed at different locations of this project, will be loaded, but the same name for the key, highest to lowest priority as follows:

                        i) file: ./ config / (config directory path to the current project);
                       II) File: ./ (current path item);
                       III) CLASSPATH: / config / (classpath config directory);
                       IIIi) CLASSPATH: / (config the classpath).

  • @propertySource introducing external file configuration profiles (the beginning of the application of non-file, class files may be stored in a context, it is also in the file system, such as: in the root directory project), can be configured to load a plurality of external profile, after loading the key may cover the front cover of the same name;
  • @Bean custom loaded PropertySourcesPlaceholderConfigurer, a plurality of external configuration files can be loaded. After loading the key may be covered with the same name in the front cover;

When a key event of the same name, the above three ways from high to low priority arrangement, the same name as key to a high-priority arrangement prevail.

 

Guess you like

Origin www.cnblogs.com/sandyflower/p/11408572.html