Please follow xiaobaiai.net or my CSDN blog.csdn.net/freeape

[TOC]

0 foreword

In the actual project development, we not only rely on the default global configuration file application. Properties to configure our project, the Spring Boot configuration file also has a lot of places to pay attention to, after mastering, can easily let us in the project to play around with various configurations. Let the configuration at a glance, clear level, clear module, written summary, and convenient later reference. As of November 21, 2019, Spring is version 5.2.1 and Spring Boot is version 2.2.1.

1 We need to know

Spring Boot provides a spring-boot-devToolsjar package, which provides some convenient application development features, mainly monitoring application changes, and then automatic restart. To use spring-boot-devtools, you need to add a dependency to pem.xml and set it to true. By default, spring-boot-devtools will only work in the development environment and will not be included by default when packaged via the Spring Boot plug-in.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>Copy the code

2 Overview and global overview

After creating a Spring Boot project, a global configuration file application.properties is generated in the SRC /main/resources directory by default, but there is nothing in it. Spring The Boot has all the default configuration parameters are automatically configured (https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.ht Ml), if we modify the Configuration in the external Configuration file, the default Configuration parameters will be modified (Externalized Configuration). There are several ways to externalize the Configuration. You can externalize the configuration using properties files, YAML files, environment variables, and command-line arguments, as described below.

For example, the configuration file can be either application.properties or application.yml, but the configuration syntax is different.

The writing:

server.port = 9090
spring.application.name = demoserviceCopy the code

Yml writing:

spring:
    application:
        name: demoservice
   server:
port: 9090Copy the code

Note: the TAB character must not be used in yML format, and there must be Spaces between colons and values.

Spring Boot overwrites parameters in one order, which we need to pay attention to. Here is an overview:

  1. When using theDevtoolsWhen,$HOME/.config/spring-bootDevtools global Settings property in the folder
  2. @TestPropertySourceAnnotations for tests
  3. The test ofproperties. in@SpringBootTestAnd test comments for testing specific parts of the application
  4. Command line arguments
  5. fromSPRING_APPLICATION_JSON(JSON embedded in environment variables or system properties)
  6. ServletConfigInitialization parameter
  7. ServletContextInitialization parameter
  8. JNDI properties:java:comp/env
  9. Java System Properties:System.getProperties()
  10. Operating system environment variables
  11. RandomValuePropertySource, its attribute is only inrandom.*In the
  12. packagingOutside of the jarProfile specific application properties (e.gapplication-{profile}.propertiesAnd the corresponding YAML variable)
  13. packagingIn the jarProfile specific application properties (e.gapplication-{profile}.propertiesAnd YAML variables)
  14. packagingOutside of the jarApplication properties (application.propertiesAnd YAML variables)
  15. packagingIn the jarApplication properties (application.propertiesAnd YAML variables)
  16. @ConfigurationOn the class@PropertySourceannotations
  17. Default properties (by settingSpringApplication.setDefaultPropertiesSpecify)

Here’s a concrete example of how the order above works:

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

@Component
public class MyBean {

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

    // ...
}Copy the code

For example, on the application classpath (packaged inside a JAR, for example), you could have an application.properties file that sets the default property value for the name property. When running in a new environment, you can provide an application.properties file outside the JAR that overwrites the application.properties file inside the JAR. Jar –name=”Spring”) or override the name attribute value. JSON ='{“name”:”test”}’ -jar myapp.jar. There are other ways to do this.

3 Setting Parameters

3.1 Parameter Setting and Loading directory sequence and Priority

There are two syntax ways to set parameters, one for properties and one for YML. SpringApplication loads the properties in the following locations from the application.properties file and adds them to the Spring environment.

  1. Of the current project directoryconfigsubdirectories
  2. Current project root directory
  3. Classpath Specifies the path in the directoryconfigsubdirectories
  4. Classpath Set directory

The above list is sorted by priority (attributes defined higher in the list will overwrite those defined lower; for example, attribute values set in 1 will overwrite those of the same attribute in 2).

Note: When building projects with Maven, the SRC /main/ Resources directory is the default classpath

In addition, here are the notes and special uses of YML.

  • Never use tabs between colons and values in YML formatMake sure there are Spaces Make sure there are Spaces Make sure there are Spaces
  • Yml double quotes do not escape special characters in strings. Special characters are printed as they are, for example
  • Yml’s single quotes will escape special characters inside the string and output the original characters
# hello\ nxiaobai.net name: "hello\nxiaobaiai.net"Copy the code
  • Yml supports objects, arrays, scalar values (strings, booleans true/false, integers, floating-point numbers, null, times, dates)new Date('1976-07-31'))
Animal: [Cat, Dog] animal: -cat-dogCopy the code

3.2 Generating Random Configuration Parameter Values

Generating random values for configuration parameters can be useful in testing or some scenarios.

As we configure:

#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}Copy the code

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

3.3 Reference between Parameters (Placeholders)

You can use placeholders to reference previously defined parameter values in configuration parameters, such as:

app.name=MyApp
app.description=${app.name} is a Spring Boot applicationCopy the code

Some prefer (for example) to use –port=9000 instead of –server.port=9000 to set configuration properties on the command line. You can enable this behavior by using placeholders in application.properties:

server.port=${port:8080}Copy the code

Note: If inherited from spring-boot-starter-parentPOm, the default filter flag for the Maven resource plug-in has been changed from ${*} to @ (i.e., @maven.token@ instead of ${maven.token}) to prevent conflicts with spring-style placeholders. If Maven filtering is enabled directly for application.properties, you may also need to change the default filter flag to another delimiter rather than @.

3.4 Customizing configuration Files

3.4.1 track way a

If you prefer not to use application.properties as the configuration file name, you can switch to another file name by specifying the spring.config.name environment property. You can also specify configuration file locations using the spring.config.location environment property (a comma-separated list of directory locations or file paths). The following example shows how to specify additional file names:

$ java -jar myproject.jar --spring.config.name=myConfigCopy the code

The following example shows how to specify two locations:

$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.propertiesCopy the code

If spring.config.location contains a directory (rather than a file), it needs to end with a /, and at run time, the configuration name from spring.config.name or the default configuration name should be appended before loading the configuration. If spring.config.location is not configured by default, search configuration files in the following order:

file:./config/
file:./
classpath:/config/
classpath:/Copy the code

Spring.config. location is used when configuring custom configuration locations, which replace the default locations. For example, if spring.config.location is configured with the values classpath:/custom-config/,file:./custom-config/, the search order changes to:

file:./custom-config/
classpath:custom-config/Copy the code

When using configuration to customize configuration locations, spring.config.additional-location uses the default location in addition to additional configuration paths. Search for other locations before the default location.

Note: In a programming environment, setting spring.config.name directly to application.properties does not take effect, except on the command line or by setting the environment variable export SPRING_CONFIG_NAME=myConfig, Or manually encode the configuration file in the specified path in the code.

3.4.2 way 2

This is done by loading the specified configuration file directly through the code. In fact, this method is the same as the custom properties described in the following section. There is only an annotation that specifies the file name. For example, if we create test.properties, the path will also be placed under SRC /main/resources:

my.app.name=hello
my.app.func=testCopy the code

Then create a new parameter Bean:

@Configuration @ConfigurationProperties(prefix="my.app") @PropertySource("classpath:test.properties") public class ConfigTestBean { private String name; private String func; // omit getter and setter}Copy the code

This is Ok, how to verify can see the custom configuration parameters section.

3.5 Cli Configuration Parameters

By default, SpringApplication converts any command-line option arguments (that is, arguments starting with –, such as –server.port=9000) to properties and adds them to the Spring environment. As mentioned earlier, command line attributes come fourth in order, always taking precedence over their underlying attribute source.

If you don’t want the command line attribute is added to the Spring environment, can be used in the program SpringApplication. SetAddCommandLineProperties disable them (false).

3.6 Profile specific Properties (Enabling profiles)

In addition to the application.properties file, you can define configuration file-specific properties using the following naming convention: application-{profile}.properties. The environment has a default set of profiles (the default profile is default, i.e. Application-default.properties). If no active profile is set, the default application-default.properties file is used. The load order and priority are the same as application.properties. Spring uses profiles to determine how applications will perform in different environments, including configuration, loading beans, dependencies, and so on. Spring’s general Profile projects include dev(development), Test (unit testing), QA (integration testing), and PROD (production). Maven also has Profile configurations. You can perform different operations during the build process for different Profile environments, including configurations, dependencies, and behaviors. Each Profile can be set: Id, properties, activation, dependencies, etc.

Speaking of which, how do I activate a profile? Here are three ways.

Application -{profile}. Properties override application-{profile}. Properties override application. Properties override application-{profile}. Properties override application. Create application-{profile}.yml as properties.

3.6.1 way a

In the configuration file, this way is not flexible, practical development is not often used

spring.profiles.active=testCopy the code

3.6.2 way 2

Use placeholders and replace them when packaging, as in Maven’s case

The first step is to add to properties (package.target is a custom parameter) :

[email protected]@Copy the code

The second step is to add the configuration for packaging different environments in pom.xml:

<! -- juxtaposed with Maven build tags --> <profiles> <! -- Development environment --> <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> <! -- Production environment --> <profile> <id>prod</id> <properties> <package.target> </profiles>Copy the code

As you can see from the above configuration, Maven has two profiles: dev and prod, and uses embedded Tomcat in dev, but not in PROd (such a configuration scenario would use external Tomcat in production and internal Tomcat in development).

The third step is to add the resource filtering implementation to modify the attributes represented by “@xxx@” at build time, using Maven’s Resources plugin:

. <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <! -- Maven build tag inside --> <resources> <! --> <resource> <directory> SRC /main/resources</directory> <resource excludes> <! Application *. Properties file --> <exclude> Application *. Properties </exclude> </excludes> </resource> <resource> <! <directory> SRC /main/resources</directory> <! --> <filtering>true</filtering> <includes> <! -- Replace the "@xx@" of the file contents with the corresponding variable, Package. target --> <include>application-${package.target}. Properties </include> </includes> </resource> </resources>Copy the code

The fourth step is to compile and package:

$MVN clean package -dmaven.test. skip=true -pdevCopy the code

3.6.3 way three

By setting system environment variables:

export SPRING_PROFILES_ACTIVE=devCopy the code

3.6.4 Other Methods

Java command line setup:

# $java-jar app.jar -- spry.profiles. Active =dev # $java-jar -Dspring. Profiles Demo - 0.0.1 - the SNAPSHOT. The jarCopy the code

Annotations (@ActiveProfiles is an annotation provided by Spring Boot’s Test starter, which is useful in unit testing and can only be used in/SRC/Test/Java) :

@ActiveProfiles("dev")Copy the code

3.6.5 YML Special Mode

A YAML file can actually be a series of line-delimited documents, each parsed separately into an expanded configuration map. Then activate dev or production as well as specifying environment variables or command lines.

Spring: profiles: dev Server: port: 9001 -- # production Spring: profiles: dev Server: port: 9001 profiles: production server: port: 0Copy the code

3.7 Customizing Attributes

Spring already provides us with many default parameters, but we can also create our own configuration parameters. For example, we create the following custom properties in application.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}Copy the code

Then create the corresponding Java parameter component 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 + "]"; }}Copy the code

The @ConfigurationProperties annotation binds all properties in the Spring Boot declaration class to the associated configuration in the configuration file. Prefix = “app” (prefix= can be omitted) : Indicates the configuration prefix and maps all attributes under the prefix. @Component or @Configuration: Adds the Component to the Spring Boot container. The Configuration takes effect only if the Component is a Component in the container.

Tip: It is also possible to read properties in the configuration file via @value (“${key}”), the key part of the file to the left of the equals sign. In the Java parameter component we defined, we can also annotate assertions for specific parameters, such as @email to the variable of the mail, and throw an exception if the injected is not a valid mail address. @assertFalse checks false, @assertTrue checks true, @decimalMax (value=10,inclusive=true) less than or equal to 10,inclusive=true, Yes ≤ or equal to @decimalmin (value=,inclusive=), @max (value=) ≤ or equal to value, @min (value=) ≤ or equal to value, @past check date, @pattern (regex=,flag=) Re and @validate verify the Po entity class, etc.

Spring-boot-configuration-processor (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> <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>Copy the code

Verify 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]Copy the code

4 summarizes

Much of the above has been verified by an actual Demo, and sample code can be found at github.com/yicm/Spring… Found on. The config files chapter is a bit more detailed, but let’s summarize it with a few points:

  • Spring Boot provides us with a large number of default configurations that can be overridden, and there are multiple ways to override (override) them, with priority among them
  • Spring Boot applications can load configuration files in different locationsapplication.properties(yml)And these positions are ordered and prioritized
  • Spring Boot parameters can be referenced by placeholders, and you can use placeholders to simplify command line parameter names
  • Spring Boot supports custom parameters
  • Spring Boot supports custom configuration file names
  • Spring Boot can support multiple configuration file switching, throughapplication-{profile}.properties(yml)Activate a profile, and there are several ways to deactivate a profile

If you know the details of the summary above, you probably know the whole blog post as well.

5 Reference Materials

  • 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-y aml
  • 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-bo ot-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

Please follow CSDNfreeape or xiaobaiai’s wechat official account or xiaobai.net