Spring Boot configuration from a zero entry 7_ latest configuration file and priority details

This article is part created, reproduced indicate the source, welcome attention to the micro-channel applet 小白AI博客micro-channel public number 小白AIor Web site xiaobaiai.net or my CSDN blog.csdn.net/freeape

[TOC]

0 Introduction

Enter the actual project development, we are not just relying on the default global configuration file application.propertiesto configure our project up, Spring Boot configuration files, there are many areas requiring attention, the master, you can easily let us do the project in midstream edge in a variety of configurations, let configuration at a glance, clear hierarchy module clear, written summary, in addition to facilitate future of reference. The content of the article is to introduce the latest configuration file content, all reference to the latest official documentation written, as of November 21, 2019, when Spring is 5.2.1version, Spring Boot is 2.2.1version.

We need to understand 1

Spring BootProvides a spring-boot-devtoolsjar package provides some convenient functions of program development, the main change is the monitoring program, and then automatically restarts. Use spring-boot-devtoolsneed to pom.xmladd a dependency in the same time needs to be set . The default will only take effect by default will not be included when packaging plug-ins . true spring-boot-devtools开发环境Spring Bootspring-boot-devtools

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>复制代码

2 Introduction and global overview

Create a Spring Bootlater project, it will src/main/resourcesby default generate a global configuration file directory application.properties, but what there is no content. Spring Boot has all the default configuration parameters are automatically configured the (https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html), if we are in an external configuration modify the configuration file, the default configuration parameters will be modified (externalized configuration, configuration externalizing ), externalizing configuration there are several ways you can use a properties file (properties file), YAML files, environment variables, and command-line arguments externalize configuration, the following content will be described in detail.

For example, the configuration file can be application.propertieseither application.yml, you can configure, just inside the configuration syntax just not the same, yml level format to clear format properties compared to some.

.propertiesWriting:

server.port = 9090
spring.application.name = demoservice复制代码

.ymlWriting:

spring:
    application:
        name: demoservice
   server:
port: 9090复制代码

Note: yml format must not use tabs must have a space between the tab, colon and values.

Spring Boot have to rewrite the parameters of (covering) a sequence, which we need to pay attention, here summarized as follows:

  1. When the Devtoolstime, $HOME/.config/spring-bootDevtools global folder set properties
  2. @TestPropertySourceFor notes on test
  3. Test properties. In @SpringBootTestproviding comments and test for testing a particular portion of the application
  4. Command line parameters
  5. From SPRING_APPLICATION_JSONproperty (JSON embedded system or environment variable properties) of
  6. ServletConfigInitialization parameters
  7. ServletContextInitialization parameters
  8. JNDI properties:java:comp/env
  9. Java system properties: System.getProperties()
  10. Operating system environment variables
  11. RandomValuePropertySource, Its properties only in random.*the
  12. Packing jar之外specific application profile attributes (e.g. application-{profile}.propertiesand the corresponding variable YAML)
  13. Package 在jar中-specific application properties to the profile (e.g., application-{profile}.propertiesand variable YAML)
  14. Packaged jar之外application properties ( application.propertiesand variables YAML)
  15. Packaged 在jar中application properties ( application.propertiesand variables YAML)
  16. @ConfigurationOn the class @PropertySourcenotes
  17. Default property (by setting SpringApplication.setDefaultPropertiesspecified)

As a specific example to illustrate how the above-described order is in effect:

import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;

@Component
public class MyBean {

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

    // ...
}复制代码

For example, in the application class path (e.g., packaging 在jar内) on, there may be a application.propertiesfile, the file is nameset default attribute property values. Run in the new environment, it can 在jar外部provide application.propertiesfile, which overrides cover 在jar内of application.properties. Another example for disposable test, can use a specific command-line switches to start (for example, java -jar app.jar --name="Spring") may be covered nameattribute value. Another example JSON format environment variable can $ java -Dspring.application.json='{"name":"test"}' -jar myapp.jarbe covered. Otherwise not one by one example.

3 configuration parameters

And the role of the order parameter settings 3.1 directory and load priority

There are two ways syntax parameter, a properties, one yml, SpringApplicationfrom the application.propertiesloading position of the following attributes of the file, and add them to Spring环境the.

  1. The current project directory configsubdirectories
  2. The root directory of the current project
  3. classpath set directory configsubdirectories
  4. set classpath directory

Above list sorted by priority (a higher position in the list of attributes defined in a lower position covering the defined attributes, the same attribute values ​​as attribute values ​​of a second attribute set in the cover).

Note: When building the project with maven, src / main / resources directory is the default classpath

Also note here that under yml points and special usage.

  • yml format must not be used between the tabs tab, colon and the value一定要有空格 一定要有空格 一定要有空格
  • yml double quotes special characters will not escape the string inside the special character output function per se, such as
  • Yml special characters will escape single quotes inside the string, the output of the original characters
# 下面会输出得到hello换行xiaobaiai.net
name: "hello\nxiaobaiai.net"
# 下面会输出得到hello\nxiaobaiai.net
name: 'hello\nxiaobaiai.net'复制代码
  • yml support object, an array, scalar (string, Boolean true / false, integer, floating point, null, time, date new Date('1976-07-31'))
# 对象行内写法
students: { name: Steve, age: 22 }
# 数组行内写法
animal: [Cat, Dog]
# 或者数组非行内写法
animal:
    - Cat
    - Dog复制代码

Generating a random configuration parameter values ​​3.2

Generating a random value in the parameter or some test scenarios is useful configuration.

As we configurations:

#random int
app.location-x=${random.int}
app.location-y=${random.int}

#random int with max
app.user-age=${random.int(100)}

#random int range
app.max-users=${random.int[1,10000]}

#random long with max
app.refresh-rate-milli=${random.long(1000000)}

#random long range
app.initial-delay-milli=${random.long[100,90000000000000000]}

#random 32 bytes
app.user-password=${random.value}

#random uuid. Uses java.util.UUID.randomUUID()
app.instance-id=${random.uuid}复制代码

Final output:locationX=-449689812, locationY=-2048116572, userAge=88, maxUsers=8927, refreshRateMilli=418859, initialDelayMilli=12542150790115755, userPassword=95ea8b43fd16dc26aad0030c1340e723, instanceId=bd252902-54e9-47b3-bebf-a81b1300ff69

3.3 parameter reference (placeholders)

Parameter values ​​can be defined in the configuration parameter prior Placeholder be realized by reference, such as:

app.name=MyApp
app.description=${app.name} is a Spring Boot application复制代码

Some people like (for example) to use --port=9000instead of --server.port=9000setting configuration property on the command line. By the application.propertiesuse 占位符to enable this behavior:

server.port=${port:8080}复制代码

Note: If you inherit from spring-boot-starter-parentPOM, the default maven plugin screening marker from the resource ${*}change @(ie, @maven.token@instead ${maven.token}) in order to prevent conflict with spring styles placeholder. If directly application.propertiesMaven filtering enabled, you might also need to change the default filter labeled as other delimiters instead @.

3.4 Custom Profile

3.4.1 a way

If you do not like to application.propertiesas a profile name, you can specify the spring.config.nameswitch to a different file name of the environment property. You can also use spring.config.locationenvironment attributes (file or directory location comma-separated list of paths) to specify the location profile. The following example shows how to specify a different file name:

$ java -jar myproject.jar --spring.config.name=myConfig复制代码

The following example shows how to specify two locations:

$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties复制代码

If spring.config.locationa directory (rather than a file), you need to /end, and running, before loading the configuration, you should be attached to the spring.config.namename of the configuration or the default configuration name. The default configuration is not spring.config.locationthe configuration file search order:

file:./config/
file:./
classpath:/config/
classpath:/复制代码

Custom configured using the arrangement position spring.config.location, they will replace the default position. For example, if spring.config.locationthe value of the configuration classpath:/custom-config/,file:./custom-config/, the search order becomes:

file:./custom-config/
classpath:custom-config/复制代码

When a custom configuration arranged position spring.config.additional-location, in addition to the additional configuration path, you will use the default location. Search for other locations before the default position.

Note: In the programming environment, is provided directly to application.properties spring.config.name is not in effect, only the command line or set environment variables export SPRING_CONFIG_NAME=myConfig, or the de-coded in the code manually import configuration file in a specified path.

3.4.2 Second way

Specified by coding directly load the configuration file to achieve, in fact, in this way with custom properties mentioned later in this section is the same, only more than a specified filename comments, more details can be seen behind the operation. For example, we create test.properties, also on a path with src/main/resourcesthe following:

my.app.name=hello
my.app.func=test复制代码

Then create a new parameter Bean:

@Configuration
@ConfigurationProperties(prefix="my.app") 
@PropertySource("classpath:test.properties")
public class ConfigTestBean {
    private String name;
    private String func;
    // 省略getter和setter
}复制代码

Ok so, how is the validation can see custom configuration parameters section.

3.5 command line configuration parameters

By default, SpringApplicationany command-line option parameters (i.e. --parameters which start, for example --server.port=9000) into property, and add them to Spring环境the. As described above, the command line in order to the fourth attribute, its priority is always below the source properties.

If you do not want to attribute to the Spring command line 环境, you can use the program SpringApplication.setAddCommandLineProperties(false)to disable them.

3.6 property-specific configuration file (activation profile)

In addition to application.propertiesthe documents, the following naming convention may be used to define a specific property profile: application-{profile}.properties. Environment has a set of default configuration file (default profile to default, i.e. application-default.properties), if the active profile is not set, the default application-default.propertiesfile, or the loading order and priority of application.propertiesthe same. SpringIt may be implementation in different environments Profile determination program, comprising a configuration, loading Bean, dependence, Springthe Profile general items comprising: dev (development), Test (unit testing), QA (integration testing), Prod (production environment). Likewise, Maven also Profile configuration may be performed during the build process for different Profile environments different operations, comprising the configuration dependent, behavior, each Profile may be provided: id (unique identifier), Properties (configuration properties), Activation (logic condition automatically triggered), dependencies (dependent) and the like.

Here, how to activate the profile it? Here are three ways.

Note: application- {profile} .properties rewrite priority is higher than the application.properties, with this configuration file 加载顺序does not matter. Also create application- {profile} .yml file with the same properties.

3.6.1 a way

In the configuration file settings, this approach is not flexible, not less actual development will be used

spring.profiles.active=test复制代码

3.6.2 Second way

A placeholder, replaced when packaged in Example Maven

The first step in adding properties in (package.target custom parameters):

[email protected]@复制代码

The second step increase in different environments packed configuration in pom.xml:

<!-- 与Maven build标记并列 -->
<profiles>
    <!-- 开发环境 -->
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <package.target>dev</package.target>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </dependency>
        </dependencies>
    </profile>
    <!-- 生产环境 -->
    <profile>
        <id>prod</id>
        <properties>
            <package.target>prod</package.target>
        </properties>
    </profile>
</profiles>复制代码

As can be seen from the above configuration, Maven of the two Profile Configuration: dev and prod, and used in the embedded dev Tomcat, whereas no prod (such as using an external Tomcat configuration scenario in a production environment, use development internal Tomcat).

The third step is to add resources to achieve modify the properties of the filter to "@ xxx @" represented in the building, use of resources Maven plug-ins:

...

<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
</plugins>

<!-- Maven build标记内 -->
<resources>
    <!-- 不加该resource也可以 -->
    <resource>
        <directory>src/main/resources</directory>
        <excludes>
            <!-- 排除掉src/main/resources下的所有application*.properties文件 -->
            <exclude>application*.properties</exclude>
        </excludes>
    </resource>
    <resource>
        <!-- 指定要处理的资源目录 -->
        <directory>src/main/resources</directory>
        <!-- 是否替换@xx@表示的maven properties属性值 -->
        <filtering>true</filtering>
        <includes>
            <!-- 将文件内容的“@xx@”替换为相应的变量,即package.target -->
            <include>application-${package.target}.properties</include>
        </includes>
    </resource>
</resources>复制代码

The fourth step is to compile the package:

# 根据Maven Profile的 dev 构建环境包
$ mvn clean package -Dmaven.test.skip=true -Pdev复制代码

3.6.3 Three ways

By setting the system environment variables:

export SPRING_PROFILES_ACTIVE=dev复制代码

3.6.4 Other ways

Java command line mode settings:

# 方式一
$ java -jar app.jar --spring.profiles.active=dev
# 方式二
$ java -jar -Dspring.profiles.active=dev demo-0.0.1-SNAPSHOT.jar复制代码

Annotations way ( @ActiveProfilesis a comment Spring Boot's Test starter provided in the unit test is more useful only in /src/test/javause):

@ActiveProfiles("dev")复制代码

3.6.5 YML special way

YAML file can actually be a ---separate line of a series of documents, each document is parsed separately mapped to an expanded configuration. Dev or production then activates the same way there are specified environment variable or command line mode of the class.

# 通用属性
server:
    port: 9000
---
# dev环境下配置
spring:
    profiles: dev
server:
    port: 9001

---
# production生产环境下配置
spring:
    profiles: production
server:
    port: 0复制代码

3.7 Custom Attributes

SpringAlready provides a lot of default parameters for us, but we can also create your own configuration parameters. For example, we application.propertiescreated the following custom properties:

#random int
app.location-x=${random.int}
app.location-y=${random.int}

#random int with max
app.user-age=${random.int(100)}

#random int range
app.max-users=${random.int[1,10000]}

#random long with max
app.refresh-rate-milli=${random.long(1000000)}

#random long range
app.initial-delay-milli=${random.long[100,90000000000000000]}

#random 32 bytes
app.user-password=${random.value}

#random uuid. Uses java.util.UUID.randomUUID()
app.instance-id=${random.uuid}复制代码

Then create the corresponding Java parameter components MyAppProperties.java:

@Component
@ConfigurationProperties("app")
    public class MyAppProperties {
    private int locationX;
    private int locationY;
    private int userAge;
    private int maxUsers;
    private long refreshRateMilli;
    private long initialDelayMilli;
    private String userPassword;
    private UUID instanceId;
    
    public int getLocationX() {
        return locationX;
    }
    public void setLocationX(int locationX) {
        this.locationX = locationX;
    }
    public int getLocationY() {
        return locationY;
    }
    public void setLocationY(int locationY) {
        this.locationY = locationY;
    }
    public int getUserAge() {
        return userAge;
    }
    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }
    public int getMaxUsers() {
        return maxUsers;
    }
    public void setMaxUsers(int maxUsers) {
        this.maxUsers = maxUsers;
    }
    public long getRefreshRateMilli() {
        return refreshRateMilli;
    }
    public void setRefreshRateMilli(long refreshRateMilli) {
        this.refreshRateMilli = refreshRateMilli;
    }
    public long getInitialDelayMilli() {
        return initialDelayMilli;
    }
    public void setInitialDelayMilli(long initialDelayMilli) {
        this.initialDelayMilli = initialDelayMilli;
    }
    public String getUserPassword() {
        return userPassword;
    }
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }
    public UUID getInstanceId() {
        return instanceId;
    }
    public void setInstanceId(UUID instanceId) {
        this.instanceId = instanceId;
    }
    
    @Override
    public String toString() {
        return "MyAppProperties [locationX=" + locationX + ", locationY=" + locationY + ", userAge=" + userAge
                + ", maxUsers=" + maxUsers + ", refreshRateMilli=" + refreshRateMilli + ", initialDelayMilli="
                + initialDelayMilli + ", userPassword=" + userPassword + ", instanceId=" + instanceId + "]";
    }
}复制代码

@ConfigurationPropertiesNotes to Spring Bootbind all the attributes and configuration file declares the class of the relevant configuration. prefix = "app"( prefix=可省略): Configure the prefix statement, all the attributes of the prefix mappings. @ComponentOr @Configuration: the components added to Spring Bootthe container, only the container assembly component is configured to take effect.

Tip: You can also @Value("${key}")read the configuration file attributes, key = propertiesKey parts of the file left of the equal sign. In Java components we define the parameters, you can also annotate the assertion of specific parameters, such as the @Email added to the message variable, if the injection is not a valid e-mail address will be thrown. Such annotations also @AssertFalsecheck false, @AssertTrueparity true, @DecimalMax(value=10,inclusive=true)less than equal to 10, inclusive = true, is less than equal @DecimalMin(value=,inclusive=), @Max(value=)less than or equal value, @Min(value=)greater than or equal value, @Pastexamination date, @Pattern(regex=,flag=)regular, @Validateto verify the like po entity class.

Finally, we need to join rely on spring-boot-configuration-processor:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!-- 加入spring-boot-configuration-processor -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>复制代码

Check our custom configuration:

@SpringBootApplication
public class Test07HelloworldApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Test07HelloworldApplication.class, args);
        MyAppProperties bean = context.getBean(MyAppProperties.class);
        System.out.println(bean.toString());
    }
}

// output
// MyAppProperties [locationX=1329054364, locationY=1100464591, userAge=99, maxUsers=8007, refreshRateMilli=733281, initialDelayMilli=54489880705550952, userPassword=76aebd15270f7065adf3d31b5a790829, instanceId=681ed3a4-a561-460c-b826-58229c31b055]复制代码

4 Summary

After most of the actual contents of the above-described verification Demo, the sample code can be github.com/yicm/Spring... found on. This chapter details the configuration file more content, but we have a few points I was like, this summary:

  • Spring Boot provides us with a lot of default configuration, we can override these values ​​for configuration parameters, and provides a variety of ways to rewrite (coverage), and between the rewrite mode is priority
  • Spring Boot application may load the configuration file in different positions application.properties(yml), and these positions is in order of priority
  • It can be referenced by the parameter placeholder between Spring Boot, but can also be simplified by the command line parameter names placeholder
  • Spring Boot can support custom parameters
  • Spring Boot supports custom configuration file name
  • Spring Boot configuration switch can support multiple file by application-{profile}.properties(yml)activating profile, and there are several ways to activate profile

If you know the specific content of the above summary, then this blog you almost have to understand.

5 References

  • https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html
  • https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-yaml
  • https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config
  • https://docs.spring.io/spring-boot/docs/2.2.1.RELEASE/api//org/springframework/boot/SpringApplication.html
  • https://docs.spring.io/spring/docs/5.2.1.RELEASE/javadoc-api/org/springframework/test/context/TestPropertySource.html
  • https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-tests
  • http://www.ruanyifeng.com/blog/2016/07/yaml.html
  • https://yaml.org/spec/1.2/spec.html
  • https://segmentfault.com/a/1190000011770028

This article is part created, reproduced indicate the source, welcome attention CSDN freeape or micro letter applet 小白AI博客micro-channel public number 小白AIor Web site xiaobaiai.net

Guess you like

Origin juejin.im/post/5dd7985a51882573412f78ec