The article has been included in
Github.com/niumoo/JavaNotes, more Java programmers need to master the core knowledge, welcome STAR and advice.


Welcome to follow me
The public,, the article is updated weekly.

Note: This Spring Boot series is based on the Spring Boot version
V2.1.1. RELEASELearning analysis is carried out, and there may be slight differences between versions.

preface

Whether you get the Spring Boot project from the official way, or quickly create the Spring Boot project from IDEA, You will find that there is a configuration file application.properties in the resource file, or it may be application.yml. This file is the configuration file for Spring Boot.

<! — more –>

1. The YAML file

In Spring Boot, the official recommendation is to use Properties or YAML file to complete the configuration. For those who do not know the YAML file format, you can check the official specific format. Here is just a brief introduction.

YAML syntax rules:

  • Case sensitive
  • Indentation denotes hierarchy
  • You can only use Spaces for indentation
  • The number of Spaces is not important, but elements of the same level should be left aligned
  • #The leading line indicates a comment

Data structures supported by YAML:

1. Simple variables, single values that cannot be divided again, such as numbers, strings, etc.

Name: Darcy age: 12 # ~ said NULL values email: ~ # multi-line string can use | retain a newline, can also use > fold line. # + preserves the newline at the end of the text block, and - deletes the newline at the end of the string. message:|- Hello world

2. Array, a set of values arranged in order.

Lang: -java-golang-c or in line lang:[Java,golang,c]

3. Objects, collections of key-value pairs.

Person :{name:Darcy,age:20} Person :{name:Darcy,age:20}

The three data structures supported by YAML can be combined to form complex composite structures.

Person: last-name: Darcy Age: 20 Birth: 2018/01/01 Email: [email protected] maps: key1: Java key2:golang lists: -a-b-c dog: name: age: 2

Note that the YAML file cannot be loaded using @PropertySource

2. The Properties file

The Properties configuration file is simple to use and can be found in a variety of configuration environments. It is simple to use, but it is not as elegant and beautiful as YAML when configuring complex structures. Take the YAML composite structure above as an example to demonstrate how the same configuration can be written in the properties file.

# Server. port=8080 # Configure property value (using an IDE to configure requires dealing with coding issues, Person.last-name = 3 person.age=18 person.birth=2018/12/06 [email protected] person.maps.key1=c Person.maps.key2 = Java person.maps.key3=golang person.lists=a,b,c,d person.dog.name= Person.dog.age=1

3. Random numbers and placeholders

RandomValuePropertySource class is useful for injection of random values (for example, injecting secret or test cases). It can generate integers, long integers, UUIDs or strings, etc. With Spring Boot, we can easily use it.

Placeholders allow previously defined variables to be referenced in configured values.

${random. Value} bootapp.number=${random. Int} bootapp.bignumber=${random . {random uuid} bootapp. Number.. Less than) ten = ${random. Int (10)} bootapp. Number. In the range = ${random. Int [1024655] 36} # Property placeholder bootapp.name=SpringBoot bootapp.description=${bootapp.name} is a Spring application

4. Use of configuration

Through the above introduction, we can find that whether using YAML or Properties can be written configuration files, but we do not know the specific use of the way, through the following several annotations, we can let us know the specific use of these configurations.

Add the required dependencies before using the configuration.

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>  </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <! Import configuration file processor, > <dependency> < grouppid >org.springframework.boot</ grouppid > <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId>  </plugin> </plugins> </build>

4.1 ConfigurationProperties

The @ConfigurationProperties annotation is an injection method using properties provided by Spring Boot. Not only can you easily bind the attribute values in the configuration file to the annotated class, but also support loose binding, JSR-303 data validation and other functions. Demonstrate the use of the @ConfigurationProperties annotation using the configuration of Properties demonstrated above.

import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Email; import java.util.Date; import java.util.List; import java.util.Map; /** * <p> * @Author niujinpeng * @Date 2018/12/6 22:54 */ @Data @Component @ConfigurationProperties(prefix = "person") @Validated public class Person { private String lastName; private Integer age; private Date birth; private Map<String, String> maps; private List<String> lists; private Dog dog; /** * Support for data validation */ @email private String Email; }
  • @Data Is a Lombok annotation that adds getting and setting methods to all properties of the class, as well as equals, canEqual, hashCode, and toString methods.
  • @ComponentAutomatically add beans to the Spring container.
  • @ConfigurationPropertiesTells the class that the properties are properties in the configuration file, and prefix specifies the prefix to read from the configuration file.

4.2 the Value

@Value supports reading values directly from a configuration file. It also supports SPEL expressions, but it does not support complex data types and data validation. Here is how to use them.

import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Email; import java.util.Date; import java.util.List; import java.util.Map; @Data @Component @Validated public class personValue {/** * Read a Value directly from the configuration file */ @Value("${person.last-name}") private String lastName; /** * Support SPEL */ @value ("#{11*4/2}") private Integer age; @Value("${person.birth}") private Date birth; /** * does not support complex type */ private Map<String, String> maps; private List<String> lists; private Dog dog; /** * does not support data validation */ @email@value (" XXX @@@@") private String Email; }

Write unit test code to test code to see if the property binding was successful.

import net.codingme.boot.domain.Person; import net.codingme.boot.domain.PersonValue; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class HelloApplicationTests { @Autowired private MockMvc mvc; @Autowired private Person person; @Autowired private PersonValue personValue; /** * @throws Exception */ @test public void testGetHello() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("Greetings from Spring Boot!" )); } /** * @ConfigurationProperties */ @Test public void TestPersion () {System.out.println(person); } /** * @test public void testPersionValue() {System.out.println(personValue);} /** * @test public void testPersionValue() {System.out.println(personValue); }}

Run and find that the data has been properly bound.

Using the above example, you can also see the difference between @ConfigurationProperties and @Value.

Characteristics of the @ConfigurationProperties @Value
function Batch injection of configuration file properties One by one
Loose binding (loose syntax) support Does not support
SpEL Does not support support
JSR-303 data validation support Does not support
The complex type support Does not support

Usage scenarios for @ConfigurationProperties and @Value.

If you just get a Value from a configuration file in some business logic, use @Value.

Say you have a Java Bean written specifically to map to a configuration file, using @ConfigurationProperties.

4.3 PropertySource

With the increasing complexity of the business and the increasing number of configuration files, we will feel that all the configuration written in a properties file will make the configuration cumbersome and unmanageable, so we want to extract the configuration of the mapping property class separately. Since Spring Boot reads application.properties by default, the separate @ConfigurationProperties(prefix = “person”) cannot read the information until after extraction. This is where you can use the @PropertySource annotation to specify the configuration file to read.

Note that @PropertySource is used to load the custom configuration file, and since the file specified by @PropertySource is loaded in priority, if the same property configuration exists in applocation. Properties, the value for the former will be overwritten.

If the extract person is configured as a single file domain-person.properties.

import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Email; import java.util.Date; import java.util.List; import java.util.Map; /** * <p> * @Author niujinpeng * @Date 2018/12/6 22:54 */ @Data @Component @Validated @PropertySource(value = "classpath:domain-person.properties") @ConfigurationProperties(value = "person") public class PersonSource { private String lastName; private Integer age; private Date birth; private Map<String, String> maps; private List<String> lists; private Dog dog; /** * Support for data validation */ @email private String Email; }

5. Multi-environment configuration

When the main configuration file is written, the file name can be application-{name}.properties. Application. Properties is used by default.

5.1 Properties Multi-environment

So how do you activate other profiles in a profile? You only need to enable the other files in Application.properties.

# Activate the application-prod.properties file spring.profiles. Active =prod

5.2 YAML multi-environment

If you are using a YAML configuration file, you can use a block of files to achieve the effect of multi-file configuration in a single YAML file. Here is how Spring Boot uses YAML files for multi-environment configuration.

Server: port: 8083 Spring: profiles: active: dev # # Specifies environment as dev # Use three -- dev --- server: port: 8085 spring: profiles: prod

5.3 Multi-environment activation mode

In addition to the above two configuration file activation methods, there are two other types of activation methods.

  • Command line, added at run time--spring.profiles.active=prod
  • JVM parameters, added at run time-Dspring.profiles.active=prod

If you need to activate the other configuration file, you can use spring. Config. Location = G: / application to configure the properties.

6. Configuration file loading order

By default, configuration files are loaded from four places, with priority from highest to lowest. A higher-priority configuration overrides a lower-priority configuration. If multiple location configurations exist at the same time, different configuration information can form complementary configurations.

-file: ./config/
-file: ./
-classpath: /config/
-classpath: /

External configuration files

Spring Boot’s external configuration files can be loaded in a number of ways. See the official documentation for details. These configurations are loaded with priority from the top to the bottom, with the higher-priority configuration overwriting the lower-priority configuration.

The sequence of several common load configurations is described below.

  1. Command line argument, all configuration can be performed on the command line, separated by multiple configuration Spaces.

    Java-jar springboot-0.0.1-snapshot.jar -- Sercer.port =9999 -- Sercer.context-path =/spring
  2. Application -{profile}.properties (or YML) file in the jar package directory
  3. Application -{profile}.properties (or YML) file in the jar package
  4. Application.properties (or YML) file in the JAR package directory
  5. Application.properties (or YML) file under the JAR package

The article code has been uploaded to GitHub Spring Boot configuration file.

The last word

The article continuously updated every week, Github.com/niumoo/JavaNotes has been included in this paper. There are more front-line big factory pilot, JAVA programmers need to master the core knowledge and other articles, also organized a lot of my words, welcome STAR and improve, I hope we become excellent together.

Articles can be helpful to click “like” in the look or Star, I like, thank you! To real-time attention to my updated articles and share dry goods, you can pay attention to the “unread code” public number, public number reply 666 can receive a lot of information.