Be serious about writing, not clickbait. Wechat search: program ape Arang.

The article is available at Github.com/niumoo/Java… And program ape Alang’s blog, point attention, don’t get lost.

Note: This Spring Boot series of articles is based on Spring Boot version V2.1.1.release, which may vary slightly.

preface

Whether you get a Spring Boot project from the official way or quickly create a Spring Boot project from IDEA, you will find a configuration file in resourceapplication.propertiesOr it could beapplication.yml. This file is the configuration file for Spring Boot.

1. The YAML file

In Spring Boot, it is recommended to use the properties file or YAML file to complete the configuration. For those who are not familiar with the YAML file format, you can check the official format.

YAML syntax rules:

  • Case sensitivity
  • Indentation indicates hierarchy
  • Indent only with Spaces
  • The number of Spaces is not important, but elements of the same rank should be left aligned
  • #The opening line represents the comment

Data structures supported by YAML:

  1. A simple variable, a single value, such as a number or string, that cannot be divided.

    name: Darcy
    age: 12
    # ~ indicates NULL
    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 - removes the newline at the end of the string.
    message:|-
      Hello world
    Copy the code
  2. An array, a set of values arranged in order.

    lang:
     - java
     - golang
     - c
    # or inline
    lang:[java,golang,c]
    Copy the code
  3. Object, a collection of key-value pairs.

    person:
      name:Darcy
      age:20
    # or inline
    person:{name:Darcy,age:20}
    Copy the code

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

# service startup port number
server:
  port: 8080
Configure the person property value
person:
  last-name: Darcy
  age: 20
  birth: 2018/ 01/01
  email: [email protected]
  maps:
    key1:java
    key2:golang
  lists:
  - a
  - b
  - c
  dog:
    name: Prosperous wealth
    age: 2
Copy the code

Note that YAML files cannot be loaded using @propertysource

2. The Properties file

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

# service startup port number
server.port=8080
# configure the property value (use IDE to configure the need to deal with coding issues, otherwise Chinese will send garbled characters)
person.last-name=Zhang SAN
person.age=18
person.birth=2018/12/06
person.email=[email protected]
person.maps.key1=c
person.maps.key2=java
person.maps.key3=golang
person.lists=a,b,c,d
person.dog.name=Prosperous wealth
person.dog.age=1
Copy the code

3. Random number and placeholder

RandomValuePropertySource class is useful for injection of random values (for example, injecting secret or test cases). It can generate integer, long integer, UUID or string, etc., through the Spring Boot package for us, we can easily use.

Placeholders allow references to previously defined variables in configured values.

# Generate random values
bootapp.secret=$ {random.value}
bootapp.number=$ {random.int}
bootapp.bignumber=$ {random.long}
bootapp.uuid=$ {random.uuid}
bootapp.number.less.than.ten=$ {random.int(10)}
bootapp.number.in.range=The ${random. Int [1024655] 36}
# placeholder for the property
bootapp.name=SpringBoot
bootapp.description=${bootapp.name} is a Spring application
Copy the code

4. Use the configuration

From the above introduction, you can see that either YAML or Properties can be used to write configuration files, but it is not known how to use them. The following comments will give you an idea of how to use these configurations.

Before using the configuration, add the required dependencies.

 <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 handler, there will be a prompt when configuring related files -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <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>
Copy the code

4.1 ConfigurationProperties

The @ConfigurationProperties annotation is an injection method provided by Spring Boot that uses properties. 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 verification and other functions. Use the configuration of Properties shown above as an example to illustrate the use of the @ConfigurationProperties annotation.

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
 * @Date2018/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 data verification */
    @Email
    private String email;

}
Copy the code
  • @Data Is a Lombok annotation that adds getting and setting methods to all attributes of the class, as well as equals, canEqual, hashCode, and toString methods.
  • @ComponentAutomatically add beans to the Spring container.
  • @ConfigurationPropertiesTells the class that its attributes are in the configuration file. Prefix specifies the prefix to read the configuration file.

4.2 the Value

@value Supports reading values directly from configuration files and SpEL expressions, but does not support complex data types and data verification. The following describes how to use @value.

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 {

    /** * reads a value */ directly from the configuration file
    @Value("${person.last-name}")
    private String lastName;

    /** * Supports SpEL expressions */
    @Value("#{11*4/2}")
    private Integer age;

    @Value("${person.birth}")
    private Date birth;

    /** * Complex types are not supported */
    private Map<String, String> maps;
    private List<String> lists;
    private Dog dog;

    /** * Data verification is not supported */
    @Email
    @Value("xxx@@@@")
    private String email;
}

Copy the code

Write unit test code to test the code to see if the property binding succeeds.


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;

    /** * simulate request test **@throws Exception
     */
    @Test
    public void testGetHello(a) throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string("Greetings from Spring Boot!"));
    }

    / * * * test@ConfigurationProperties* /
    @Test
    public void testPersion(a) {
        System.out.println(person);
    }

    / * * * test@ValueIntroduces the configuration value */
    @Test
    public void testPersionValue(a) { System.out.println(personValue); }}Copy the code

The run discovery data is properly bound.

You can also see the difference between @ConfigurationProperties and @Value from the example above.

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

Usage scenarios for @ConfigurationProperties and @Value.

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

If you write a Java Bean specifically to map to a configuration file, use @ConfigurationProperties.

4.3 PropertySource

With the increase of business complexity, there are more and more configuration files. We think that writing all the configuration in a properties file will make the configuration complicated and not conducive to management. Therefore, we hope to extract the configuration of the mapping attribute class separately. Since Spring Boot reads application.properties by default, the single @ConfigurationProperties(prefix = “person”) prior to extraction cannot read the information. This is done using the @propertysource annotation to specify which configuration file to read.

Note that the custom configuration file is loaded using @propertysource. Since the file specified by @propertysource is loaded first, the same property configuration in applocation. Properties overrides the values in the former.

If person is extracted and configured as a separate 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
 * @Date2018/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 data verification */
    @Email
    private String email;
}
Copy the code

5. Configure multiple environments

When the main configuration file is written, the file name can be application-{name}.properties. The default is application.properties.

5.1 Properties Multiple environments

So how do I activate other profiles in a profile? Only other files need to be enabled in application.properties.

# Activate the application-prod.properties file
spring.profiles.active=prod
Copy the code

5.2 YAML Multi-environment

If you are using a YAML configuration file, you can use a file block to configure multiple files in a SINGLE YAML file. Here is how Spring Boot uses a YAML file to configure multiple environments.

server:
  port: 8083
  profiles:
    active: dev # set the environment to dev
# Use three -- for document block differentiation
---
server:
  port: 8084
spring:
  profiles: dev
---
server:
  port: 8085
spring:
  profiles: prod
Copy the code

5.3 Multi-environment Activation Mode

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

  • Command line, run time add--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. Configure the file loading sequence

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

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

7. External configuration files

The external configuration file of Spring Boot can be loaded in many ways. For details, refer to the official documentation. The write configuration is loaded from highest priority to bottom. The configuration with a higher priority overrides the configuration with a lower priority.

The following describes several common loading configuration sequences.

  1. All configurations can be executed on the command line. Multiple configurations are separated by Spaces.
Jar --server.port=9999 --sercer.context-path=/springCopy the code
  1. Application -{profile}. Properties (or yML) file in the jar package directory
  2. Application -{profile}. Properties (or yML) file in jar package
  3. Application. Properties (or yML) file in the jar package directory
  4. Application. Properties (or yML) file in the jar

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

Hello world 🙂

I am a lang, lang of the moon, a technical tool person who moves bricks every day. Personal website: www.wdbyte.com If you want to subscribe, you can follow the public account of “Procedural Ape Alang”, or the blog of procedural ape Alang, or add me on wechat (WN8398).

This article has also been compiled at GitHub.com/niumoo/Java… Welcome Star.