(3) Spring Boot configuration file, loading order, configuration principle

Article content :

  • Basic use of SpringBoot configuration file;
  • Explain the priority of the yaml configuration file;
  • yaml configuration file directory and comparison instructions;
  • Custom configuration properties;
  • Comparison of two annotations @ConfigurationProperties and @Value;
  • Idea custom yaml configuration tips
  • Load external configuration;
  • Assembly configuration file (properties, yaml);
  • Introduce xml configuration file.

First, the basic use of SpringBoot configuration file

(1) SpringBoot uses a global configuration file, the configuration file name is fixed;

  • application.properties
  • application. marl
  • YAML basic syntax
       – Use indentation to represent hierarchical relationships
       – Tab keys are not allowed when indenting , only spaces are allowed .
       – The number of indented spaces is not important, as long as the elements of the same level are aligned on the left
       – Case sensitive
  • Three data structures supported by YAML
     – Object: a collection of key-value pairs
     – Array: a set of values ​​arranged in order
     – Literals: single, indivisible values

(2) Practice conclusion: in the same directory , properties configuration priority> YAML configuration priority.

                           Therefore, we can bring the configuration of properties when the jar package starts to override the configuration

(3) Configuration file directory:

     The SpringBoot configuration file can be placed in multiple paths, and the configuration priority under different paths is different. Placeable directory (priority from high to low)

  1. file: ./ config / (current project path config directory);
  2. file: ./ (under the current project path);
  3. classpath: / config / (under the classpath config directory);
  4. classpath: / (under classpath config). 

The priority is from high to low, and the high-priority configuration will override the low-priority configuration ; SpringBoot will load all configuration files from these four locations and complement the configuration ;

  •   Path dependent class: ConfigFileApplicationListener

    

      The DEFAULT_SEARCH_LOCATIONS attribute sets the loaded directory; in the getSearchLocations () method, the comma is parsed into a Set, and the internal class Loader is responsible for the loading process of this configuration file, including loading the configuration of the specified environment of the profile , in the form of application + '-' + name Load .

private Set<String> getSearchLocations() {
      if (this.environment.containsProperty("spring.config.location")) {
         return this.getSearchLocations("spring.config.location");
        } else {
                Set<String> locations = 
           this.getSearchLocations("spring.config.additional-location");
                locations.addAll(
                   this.asResolvedSet(ConfigFileApplicationListener.this.searchLocations, 
                  "classpath:/,classpath:/config/,file:./,file:./config/"));
                return locations;
            }
        }

  After adding to the List, reverse the collection order:

private Set<String> asResolvedSet(String value, String fallback) {
            List<String> list = Arrays.asList(StringUtils.trimArrayElements
                  (StringUtils.commaDelimitedListToStringArray(value != null ? 
                       this.environment.resolvePlaceholders(value) : fallback)));
            Collections.reverse(list);
            return new LinkedHashSet(list);
        }

 In summary:

   Next, take the port configuration as an example

  1. Set the port to 8888 in the configuration file under the resources / directory;
  2. The configuration file in the resources / config directory sets the port to 9999;
  3. Set the port to 6666 in the configuration file under the project path;
  4. The configuration file in the project path config directory sets the port to 7777;

               å¨è¿éæå ¥ å¾çæè¿ °

Final operation result:

  

Through the control variable method, it can be demonstrated
that the priority is from high to bottom, and the configuration of high priority will override the configuration of low priority

Second, static resource access rules, custom static file configuration method

Third, the way the configuration file binds the value to the bean

(1) Use @ConfigurationProperties annotation + @ Component in Spring Boot

@Component
@ConfigurationProperties(locations = "classpath:mail.properties", 
                                     ignoreUnknownFields = false, prefix = "mail")
public class MailProperties {
    private String host;
    private int port;
    private String from;
    private String username;
    private String password;
    private Smtp smtp;
}

(2) @ Bean + @ ConfigurationProperties for binding

    @Bean
    @ConfigurationProperties(locations = "classpath:mail.properties", prefix = "mail")
    public MailProperties mailProperties(){
        MailProperties mp = new MailProperties();
        System.out.println("zheli " + mp);
        return mp;

    }

  (3) @ConfigurationProperties + @EnableConfigurationProperties, and then use Spring's @Autowireto inject the mail configuration bean:

@ConfigurationProperties(locations = "classpath:mail.properties", 
                                ignoreUnknownFields = false, prefix = "mail")
public class MailProperties {
    private String host;
    private int port;
    private String from;
    private String username;
    private String password;
    private Smtp smtp;
}

Method (3) requires @EnableConfigurationProperties (Person.class) at the end to make @ConfigurationProperties: effective

Then in the startup class, configure @EnableConfigurationProperties as follows, and then inject @Autowired where it is used

@SpringBootApplication
@EnableConfigurationProperties(MailProperties.class)
public class TestProperty1 {

    @Autowired
    private MailProperties mailProperties;

}

Fourth, @Value gets the value and @ConfigurationProperties gets the value comparison

Note : they can get the value in the configuration file yml or properties; ( complex types such as maps, lists, etc. )

  • If we say that we just need to get a value in the configuration file in a certain business logic, use @Value;
  • If we say that we specially wrote a javaBean to map with the configuration file, we will use @ConfigurationProperties directly;

Data verification is added to the configuration file:

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
     * <bean/>
     */

   //lastName必须是邮箱格式
    @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

Six, load the specified configuration file

(1)@PropertySource&@ImportResource&@Bean

  • @ PropertySource : load the specified configuration file;
/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 *      prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 *
 * 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
 *  @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;
 *
 */
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
     * <bean/>
     */

   //lastName必须是邮箱格式
   // @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;
  • @ ImportResource : Importing Spring configuration file, so that the contents of the configuration file which is to take effect;

    There is no Spring configuration file in Spring Boot, and the configuration file we wrote ourselves cannot be automatically recognized;

    I want Spring's configuration file to take effect and load it in; @ImportResource is marked on a configuration class

@ImportResource(locations = {"classpath:beans.xml"})
导入Spring的配置文件让其生效

To write Spring configuration files

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>

SpringBoot recommends adding components to the container ; it is recommended to use the full annotation method

1. Configuration class @Configuration ------> Spring configuration file

2. Use @Bean to add components to the container

/**
 * @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件
 *
 * 在配置文件中用<bean><bean/>标签添加组件
 *
 */
@Configuration
public class MyAppConfig {

    //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService02(){
        System.out.println("配置类@Bean给容器中添加组件了...");
        return new HelloService();
    }
}

 

Published 108 original articles · Like 58 · Visits 50,000+

Guess you like

Origin blog.csdn.net/qq_41893274/article/details/104712405