Details of Spring Boot configuration file

Details of Spring Boot configuration file

Spring Boot provides two commonly used configuration files, properties file and yml file. Their role is to modify the default value of Spring Boot auto configuration. Compared with the properties file, the yml file is younger and has many pits. yml determines the hierarchical relationship through spaces, which makes the structure of the configuration file clearer, but also destroys the hierarchical relationship due to insignificant spaces. This chapter focuses on the syntax of yml and taking values from configuration files. What are you waiting for? Come to study!

Technology: yaml, properties syntax, ConfigurationProperties and Value annotation, configuration file placeholder

Note: this chapter focuses on the syntax of yaml and the use of configuration properties annotation. Please move to github for test code and complete code. You can click a star if you like.

Source code: https://github.com/ITDragonBlog/daydayup/tree/master/SpringBoot/spring-boot-yml

Article directory structure:

1, About YAML

yml is a file of YAML (YAML Ain't Markup Language), which takes data as the center and is more suitable for configuration files than json and xml

Compared with xml, yml has less structured code, which makes the data more direct and clear at a glance.

What about yml and json? No one is good or bad, the right is the best. The syntax of yml is more elegant than json, and the annotation is more standard, which is suitable for configuration files. As a machine exchange format, json is better than yml, and is more suitable for data exchange of api calls.

1) YAML syntax

Controls the hierarchy by the indentation of spaces. The number of spaces is not important, as long as the left space is aligned, it is considered the same level. Note that you cannot replace spaces with tab s. And case sensitive. It supports three data structures: literal, object and array, and also supports compound structure.

Literal: string, boolean type, value, date. Strings are not quoted by default, and single quotes escape special characters. Date format supports yyyy/MM/dd HH:mm:ss

Object: it is composed of key value pairs and data in the form of key: (space) value. The space after the colon is required. Each group of key value pairs occupies one line, and the degree of indentation should be the same. You can also use the inline writing method: {K1: V1,.... kn: VN}

Array: consists of data with the shape of - (space) value. The space after the dash is required. Each group of data occupies one line, and the degree of indentation should be the same. You can also use the inline writing method: [1,2,...n]

Composite structure: any combination of the above three data structures

2) Application of YAML

Create a global configuration file for Spring Boot application.yml , configure the property parameters. It mainly includes string, string with special characters, boolean type, value, set, inline set, inline object, and set object.

yaml:
  str: Strings can be unquoted
  specialStr: "Double quotation mark direct output\n Special characters"
  specialStr2: 'Single quotes can be escaped\n Special characters'
  flag: false
  num: 666
  Dnum: 88.88
  list:
    - one
    - two
    - two
  set: [1,2,2,3]
  map: {k1: v1, k2: v2}
  positions:
    - name: ITDragon
      salary: 15000.00
    - name: ITDragonBlog
      salary: 18888.88

Create entity class YamlEntity.java Get the property value in the configuration file, get the specified value in the configuration file by annotation @ ConfigurationProperties and inject it into the entity class. Its specific test method and the principle of obtaining value, please continue to look back!

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * YAML Syntax entity class
 * Remember:
 * 1, Colon followed by a space, that is, key: (space) value
 * 2, The number of spaces on the left of each line of parameter determines the level of the parameter, which cannot be entered randomly.
 */
@Component
@ConfigurationProperties(prefix = "yaml")
public class YamlEntity {

    // Literal, string, Boolean, numeric
    private String str; // Normal string
    private String specialStr; // Escape special string
    private String specialStr2;// Output special string
    private Boolean flag;   // Boolean type
    private Integer num;    // integer
    private Double dNum;    // decimal

    // Array, List and Set are written in two ways: First: - space value, each value occupies one line, and needs to be indented and aligned; second: [1,2,...n] in line writing
    private List<Object> list;  // list repeatable set
    private Set<Object> set;    // Set non repeatable set

    // Map and entity class are written in two ways: first, key space value, each value occupies one line, and needs to be indented and aligned; second, write in line {key: value,....}
    private Map<String, Object> map; // Map K-V
    private List<Position> positions;  // Composite structure, collection object

    // Omit getter, setter, toString methods
}

3) YML summary

1, String can be quoted. If double quotation marks are added, special characters will be output. If single quotation marks are not added, special characters will be escaped;

2, Array type, space after dash; object type, space after colon;

3, YAML controls the hierarchical relationship with the degree of space indentation, but it can't replace space with tab key, which is case sensitive;

4, How to crash a programmer? Add a few spaces to the yml file! ("> dish <)

2, About Properties

We often use the properties file. Here is a brief introduction. Its syntax structure is as follows: key=value. Pay attention to the problem of Chinese scrambling. It needs to be transcoded to ASCII. The details are as follows:

userinfo.account=itdragonBlog
userinfo.age=25
userinfo.active=true
userinfo.created-date=2018/03/31 16:54:30
userinfo.map.k1=v1
userinfo.map.k2=v2
userinfo.list=one,two,three
userinfo.position.name=Java architect 
userinfo.position.salary=19999.99

The value from the configuration file is injected into the entity class, which is the same as YAML.

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * User information
 * @ConfigurationProperties : All properties in the decorated class are bound to the specified value in the configuration file, which is found by prefix
 */
@Component
@ConfigurationProperties(prefix = "userinfo")
public class UserInfo {

    private String account;
    private Integer age;
    private Boolean active;
    private Date createdDate;
    private Map<String, Object> map;
    private List<Object> list;
    private Position position;

   // Omit getter, setter, toString methods
}

3, Configuration file value

Spring Boot obtains properties from the configuration file through the ConfigurationProperties annotation. From the above example, we can see that the ConfigurationProperties annotation can specify the data to be imported in batch by setting prefix. Support to obtain complex data such as literal Value, collection, Map, object, etc. Is there any other feature of the ConfigurationProperties annotation? What's the difference between it and spring's Value annotation? With these questions in mind, let's move on. (๑•̀ㅂ•́)و✧

1) Advantages and disadvantages of ConfigurationProperties and Value

Advantages and disadvantages of configuration properties annotation

1, You can batch inject attributes from the configuration file;

2, Support the acquisition of complex data types;

3, Lower requirements for attribute name matching, such as user name, user_ name,userName,USER_ Name can be taken;

4, Support JAVA's JSR303 data verification;

5, The disadvantage is that it does not support strong SpEL expressions;

The advantages and disadvantages of Value annotation are just the opposite. It can only configure injection values one by one; it does not support complex data types such as arrays and collections; it does not support data validation; it has strict requirements for attribute name matching. The biggest feature is to support the SpEL expression, so that it has more functions.

2) Details of @ ConfigurationProperties

Step 1: import dependencies. To use the configuration properties annotation, you need to import a spring boot configuration processor dependency;

Step 2: configure the data. stay application.yml In the configuration file, configure the attribute parameters with itdragon prefix. The parameters have literal value and array, which are used to judge whether the ability to obtain complex attributes is supported;

Step 3: match the data. Add the annotation ConfigurationProperties to the class and set the prefix property value to itdragon. And add the class to Spring's IOC container.

Step 4: verify the data. Add the data validation annotation, enable data validation, and test whether it supports the data validation function;

Step 5: test whether the configuration properties annotation supports the SpEL expression;

Import dependency: pom.xml Add spring boot configuration processor dependency

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>

Configuration data: application.yml Configure attribute parameters. Nick name is used to determine the looseness of matching attributes. If it is replaced by nick_name can still get the value.

itdragon:
  nick-name: ITDragonBlog
  email: 1234567890@qq.com
  iphone: 1234567890
  abilities: [java, sql, html]
  created_date: 2018/03/31 15:27:30

Match and verify 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;
/**
 * ConfigurationProperties Annotation syntax class
 * Step 1: import depends on spring boot configuration processor;
 * Step 2: add the class modified by the ConfigurationProperties annotation to Spring's IOC container;
 * Step 3: set the prefix attribute and specify the prefix of the attribute to be injected;
 * Step 4: add data verification notes and enable data verification;
 *
 * Note:
 * 1, In the yml configuration file, the corresponding parameters of nickName and createdDate are dash and underline respectively, which are used to test the looseness of attribute name matching
 * 2, email and iphone test to support JSR303 data verification
 * 3, Cap abilities test to support complex data structures
 */
@Component
@ConfigurationProperties(prefix = "itdragon")
@Validated
public class ConfigurationPropertiesEntity {

    private String nickName;    // Parsing succeeded, supporting loose matching attribute
    private String email;
//    @Email / / parsing failed, data validation succeeded: BindValidationException: Binding validation errors on itdragon
    private String iphone;
    private List<String> abilities;
    private Date createdDate;   // Parsing succeeded, supporting loose matching attribute

//    @ConfigurationProperties("#{(1+2-3)/4*5}")
    private String operator;    // Syntax error reporting, does not support SpEL expression: not applicable to field

    // Omit getter, setter, toString methods
}

3) @ Value details

Last blog The use of the Value annotation has been described. Here is a brief description.

Step 1: add the Value annotation on the attribute, and inject the Value from the configuration file through ${} setting parameter;

Step 2: modify${ itdragon.ceatred_ Parameter value in date}, change to${ itdragon.ceatredDate }Test whether the resolution is successful;

Step 3: add the data validation annotation, enable data validation, and test whether it supports the data validation function;

Step 4: test whether the Value annotation supports the SpEL expression;

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;
/**
 * Value Annotation syntax class
 * Step 1: add the annotation Value injection parameter to the attribute
 * Step 2: add the class modified by Value annotation to Spring's IOC container;
 * Step 3: add data verification notes to check whether data verification is supported;
 *
 * Note:
 * 1, In the yml configuration file, the corresponding parameters of nickName and createdDate are dash and underline respectively, which are used to test the looseness of attribute name matching
 * 2, email and iphone test to support JSR303 data verification
 * 3, Cap abilities test to support complex data structures
 *
 * Conclusion:
 * 1, The createDate value must be consistent with the parameters in the yml configuration file,
 * 2, You can still pass the test even if you add a mailbox verification annotation to the iphone,
 * 3, Complex data structure is not supported, and the prompt error is the same as the first one: IllegalArgumentException: Could not resolve placeholder 'itdragon.abilities' in value "${itdragon.abilities }
 */
@Component
@Validated
public class ValueEntity {

    @Value("${itdragon.nick-name}")
    private String nickName;
    @Value("${itdragon.email}")
    private String email;
    @Email
    @Value("${itdragon.iphone}")        // Parsing succeeded, data verification is not supported
    private String iphone;
//    @Value("${itdragon.abilities }") / / parsing error, complex data structure is not supported
    private List<String> abilities;
//    @Value("${itdragon.ceatredDate }") / / parsing error. Loose matching attribute is not supported. It must be strictly consistent
    private Date createdDate;

    // Powerful side of Value annotation: support for SpEL expression
    @Value("#{(1 + 2-3) / 4 * 5} ") / / arithmetic operation
    private String operator;
    @Value("#{1 > 2 | 2 < = 3} ") / / relational operation
    private Boolean comparison;
    @Value("#{systemProperties['java.version ']}') / / system configuration: os.name
    private String systemProperties;
    @Value("#{T ( java.lang.Math ). ABS (- 18)} ") / / expression
    private String mapExpression;

    // Omit getter, setter, toString methods
}

4) Summary of configuration file values

1, The configuration properties annotation supports batch injection, while the Value annotation is suitable for single injection;

2, The ConfigurationProperties annotation supports data validation, while the Value annotation does not;

3, The ConfigurationProperties annotation supports loose matching properties, while the Value annotation must match properties strictly;

4, ConfigurationProperties does not support strong SpEL expressions, while Value does;

4, Placeholder for profile

Placeholders and random numbers are relatively simple, so you can paste the code directly here. It should be noted that:

1, Placeholder value must be full path

2, Placeholder set default, no space after colon

ran:  # The prefix here cannot be random,
  ran-value: ${random.value}
  ran-int: ${random.int}
  ran-long: ${random.long}
  ran-int-num: ${random.int(10)}
  ran-int-range: ${random.int[10,20]}
  ran-placeholder: placeholder_${ran.ran-value:There can be no spaces here, and key Is the full path}
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * Random numbers and placeholder syntax classes
 */
@Component
@ConfigurationProperties(prefix = "ran")
public class RandomEntity {

    private String ranValue;    // Randomly generate a string
    private Integer ranInt;     // Randomly generate an integer
    private Long ranLong;       // Randomly generate a long integer
    private Integer ranIntNum;  // Randomly generate an integer within the specified range
    private Integer ranIntRange;// Randomly generate an integer in a specified interval
    private String ranPlaceholder;// placeholder 

    // Omit getter, setter, toString method e
}

Test code:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootYmlApplicationTests {

	@Autowired
	private UserInfo userInfo;
	@Autowired
	private YamlEntity yamlEntity;
	@Autowired
	private ConfigurationPropertiesEntity configurationPropertiesEntity;
	@Autowired
	private ValueEntity valueEntity;
	@Autowired
	private RandomEntity randomEntity;

	@Test
	public void contextLoads() {
//		System.out.println("YAML Grammar : " + yamlEntity);
//		System.out.println("UserInfo : " + userInfo);
//		System.out.println("ConfigurationProperties Grammar : " + configurationPropertiesEntity);
//		System.out.println("Value Grammar : " + valueEntity);
		System.out.println("Random Grammar : " + randomEntity);
	}

}

5, Summary

1, Spring Boot supports two kinds of configuration files, among which YAML data structure is clearer than properties.

2, YAML is a special language for writing configuration files, which is very simple and powerful.

3, YAML has strict requirements on space, and can't be replaced by Tab key.

4, YAML determines the level by the degree of space indentation, with spaces after colons and spaces after dashes.

5, The ConfigurationProperties annotation is suitable for batch injection of properties in the configuration file, and the Value annotation is suitable for obtaining an item in the configuration file.

6, The ConfigurationProperties annotation supports data validation and obtaining complex data, and the Value annotation supports the SpEL expression.

This is the end of the article. If the article is helpful to you, you can click "recommend" or "follow" me to get more knowledge.

Here are some contents in the column table of blog article catalog. If you are interested in content, you can click the link on the right: http://www.cnblogs.com/itdragon/p/8709948.html

Keywords: Java Spring Attribute JSON

Added by The_Black_Knight on Sun, 21 Jun 2020 08:20:11 +0300