The Spring Boot configuration file is detailed

Source: Internet
Author: User
Tags parse error

The Spring boot configuration file is detailed

Spring boot provides two commonly used configuration files, the properties file and the Yml file. Their role is to modify the default values for spring boot auto-configuration. Compared to the properties file, the Yml file is much younger and has many pits. Can be described as Analyticals defeat Xiao, yml through the space to determine the hierarchical relationship, is the configuration file structure and clear, but also because of insignificant space to destroy the hierarchical relationship. This chapter focuses on the syntax of YML and the values that are taken from the configuration file. What are you waiting for, hurry up and learn!

Techniques: Yaml, properties syntax, use of configurationproperties and value annotations, use of configuration file placeholders

Description: This chapter focuses on the syntax of YAML and the use of configurationproperties annotations, test code and complete code please go to GitHub and your favorite friends can point to a star.

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

Article Directory structure:

I. Introduction of YAML

YML is a file of Yaml (Yaml Ain ' t Markup Language) language, data-centric, more suitable for configuration files than JSON, XML, etc.

YML is less structured code than XML, which makes the data more straightforward and at a glance.

What about YML and JSON? No one is good or bad, the best is the right one. YML's syntax is more elegant than JSON, and annotations are more standard and suitable for configuration files. As a machine Exchange format, JSON is stronger than YML, and it is more suitable for making API call data exchange.

A) Yaml syntax

Controls the hierarchical relationship with the degree of indentation of a space. The number of spaces is not important, as long as the left space alignment is considered the same level. Note You cannot use tab instead of spaces. and case sensitive. Supports literals, objects, arrays of three data structures, and also supports composite structures.

Literal value : String, Boolean type, numeric, date. Strings are not quoted by default, and single quotes escape special characters. Date format support YYYY/MM/DD HH:MM:SS

Object : Consists of a key-value pair, shaped like key: (space) the data of value. The spaces after the colon are necessary, each set of key-value pairs takes one line, and the indentation is consistent, or inline notation can be used: {k1:v1, .... kn:vn}

Array : Consists of data that is shaped as -(space) value . The space behind the dash is a must, each group of data occupies one row, and the degree of indentation is consistent, you can also use inline notation: [,... N]

Composite structure : Any combination of the above three data structures

(ii) Use of YAML

Create a Spring Boot global profile application.yml, and configure the attribute parameters. There are several commonly used data formats, such as strings, strings with special characters, Boolean types, values, collections, inline collections, inline objects, collection objects, and so on.

Yaml:  Str:Strings can be unquotedSpecialstr: "double quotes directly output \ n special characters"  SPECIALSTR2: ' single quotes can escape \ n Special characters '  flag:FalseNum:666Dnum:88.88list:    -One-Both-BothSet: [1,2,2,3]  Map: {K1:V1, K2:V2}  Positions:    - Name:ItdragonSalary:15000.00- Name:ItdragonblogSalary:18888.88

Create an entity class Yamlentity.java gets the value of the property in the configuration file, gets the specified value from the configuration file and injects it into the entity class through the annotation @configurationproperties. Its specific test methods and the principle of obtaining values, 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 points:* One, after the colon plus a space, that is, key: (space) value* Second, the number of left space on each line of the parameter determines the level of the parameter, non-random input.  */@Component@ConfigurationProperties(prefix ="Yaml") Public classyamlentity {//Literal, String, Boolean, numeric    PrivateString str;//Normal string    PrivateString Specialstr;//Escape Special strings    PrivateString specialStr2;//Output Special string    PrivateBoolean Flag;//Boolean type    PrivateInteger num;//Integer    PrivateDouble Dnum;//Decimal    //array, list and set, two ways:-The first type:-Space value, each value for a row, need to indent the alignment; the second: [,... N] in line notation    PrivateList<object> list;//List repeatable collection    PrivateSet<object> set;//Set non-repeating collection    //Map and entity classes, two ways: the first: Key space value, one row for each value, indent alignment, and the second: {Key:value,....} in line notation    PrivateMap<string, object> map;//Map k-v    PrivateList<position> positions;//Composite structure, collection Object    //Omit Getter,setter,tostring method}
III) Summary of YML

One, the string can be without quotation marks, if the double quotation marks the output of special characters, if not add or add single quotation marks to escape the special characters;

Second, the array type, the short line should be followed by a space, the object type, the colon followed by a space;

Three, Yaml is the degree of space indentation to control the hierarchical relationship, but can not use the TAB key to replace the space, case sensitive;

Iv. How to make a programmer crash? Add a few spaces to the Yml file! (〃> dishes)

Second, the properties of the introduction

Properties file you often use, here is a brief introduction. Its grammatical structure is as follows: Key=value. Note Chinese garbled problem, need to transcode into ASCII. The following are the specific examples:

userinfo.account=itdragonBloguserinfo.age=25userinfo.active=trueuserinfo.created-date=2018/03/31 16:54:30userinfo.map.k1=v1userinfo.map.k2=v2userinfo.list=one,two,threeuserinfo.position.name=Java架构师userinfo.position.salary=19999.99

Injecting values from a configuration file into an entity class 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 (this value is found through prefix) */@Component@ConfigurationProperties(prefix ="UserInfo") Public classUserInfo {PrivateString account;PrivateInteger age;PrivateBoolean active;PrivateDate CreatedDate;PrivateMap<string, object> map;PrivateList<object> list;PrivatePosition Position;//Omit Getter,setter,tostring method}
Third, the configuration file value

Spring boot Gets the properties from the configuration file by configurationproperties annotations. As you can see from the example above, configurationproperties annotations can be set prefix to specify data that needs to be imported in bulk. Support for obtaining complex data such as literals, collections, maps, objects, and more. Configurationproperties annotations Are there any other special? What is the difference between it and spring's value annotation? With these questions, we continue to look down. (??????)??

A) advantages and disadvantages of configurationproperties and value

Advantages and disadvantages of configurationproperties annotations

One, you can bulk injection of attributes from the configuration file;

Second, to support the acquisition of complex data types;

Third, the property name matching requirements are low, such as user-name,user_name,username,user_name can be taken value;

Four, support Java JSR303 data verification;

Five, the disadvantage is not support strong spel expression;

The advantages and disadvantages of value annotations are the opposite, it can only be configured to inject values, not support complex data types such as arrays, collections, data validation is not supported, and there are strict requirements for property name matching. The biggest feature is the support for Spel expressions, which makes them more versatile.

II) @ConfigurationProperties Detailed

First step: Import dependencies. To use configurationproperties annotations, you need to import dependent spring-boot-configuration-processor;

Step Two: Configure the data. In the APPLICATION.YML configuration file, the configuration attribute parameter, which is prefixed with Itdragon, has literals and arrays to determine whether the ability to acquire complex attributes is supported;

Step three: Match the data. Add the annotation configurationproperties on the class and set the Prefix property value to Itdragon. and add the class to spring's IOC container.

Fourth step: Verify the data. Add data check validated annotations, turn on the data check, test whether it supports the function of data check;

Fifth step: Test whether configurationproperties annotations support spel expressions;

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 configuration attribute parameters, Nick-name is used to determine the loose property of the matching attribute, if replaced by Nick_name can still get the value.

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

Match and validate 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* First step: import dependent spring-boot-configuration-processor;* Step Two: Add the configurationproperties annotation-modified class to spring's IOC container;* Step Three: Set the Prefix property to specify the prefix that needs to be injected into the attribute;* Fourth Step: Add data Check annotations, turn on data check; ** Note the point:* One, nickname and CreatedDate in the YML configuration file, the corresponding parameters are underlined and underlined to test their loose property name matching* Second, email and iphone test its support JSR303 data check* Third, abilities test its support for complex data structures */@Component@ConfigurationProperties(prefix ="Itdragon")@Validated Public classconfigurationpropertiesentity {PrivateString nickname;//parse succeeded, support loose match attribute    PrivateString email;//@Email//parse failed, data check successful: bindvalidationexception:binding validation errors on Itdragon    PrivateString iphone;PrivateList<string> abilities;PrivateDate CreatedDate;//parse succeeded, support loose match attribute//@ConfigurationProperties ("#{(1+2-3)/4*5}")    PrivateString operator;//Syntax error, SPEL expression not supported: applicable to field    //Omit Getter,setter,tostring method}
III) @Value detailed

The previous blog has introduced the use of value annotations, which are simply explained here.

Step One: Add value annotations on attributes, and inject values from the configuration file with ${} setting parameters;

The second step: Modify ${itdragon.ceatred_date} The parameters in the value, to ${itdragon.ceatredDate} test whether it can be resolved successfully;

The third step: Add data Check validated annotation, turn on the data check, test whether it supports the function of data check;

Fourth step: Test whether the value annotations support spel expressions;

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* First step: Add annotations on attributes value injection parameters* Step Two: Add the class of value annotation adornment to spring's IOC container;* Step three: Add data validation Annotations to check whether data validation is supported; ** Note the point:* One, nickname and CreatedDate in the YML configuration file, the corresponding parameters are underlined and underlined to test their loose property name matching* Second, email and iphone test its support JSR303 data check* Third, abilities test its support for complex data structures ** Conclusion:* First, the CreateDate value must be consistent with the parameters in the yml configuration file,* Second, both on the iphone to add email verification annotations can still pass the test,* Three, does not support the complex data structure, the prompt error and the first one is the same: Illegalargumentexception:could not resolve placeholder ' itdragon.abilities ' in value "${ Itdragon.abilities} " */@Component@Validated Public classvalueentity {@Value("${itdragon.nick-name}")PrivateString nickname;@Value("${itdragon.email}")PrivateString email;@Email    @Value("${itdragon.iphone}")//parse succeeded, data check not supported    PrivateString iphone;//@Value ("${itdragon.abilities}")//Parse error, does not support complex data structures    PrivateList<string> abilities;//@Value ("${itdragon.ceatreddate}")//Parse error, does not support loose match attributes, must be strictly consistent    PrivateDate CreatedDate;//The powerful side of the value annotations: support for spel expressions    @Value("#{(1+2-3)/4*5}")//Arithmetic operations    PrivateString operator;@Value("#{1>2 | | 2 <= 3} ")//Relational Operations    PrivateBoolean comparison;@Value("#{systemproperties[' java.version '}")//System configuration: Os.name    PrivateString systemproperties;@Value("#{t (Java.lang.Math). ABS ( -18)}")//Expression    PrivateString mapexpression;//Omit Getter,setter,tostring method}
Iv. Summary of configuration file values

Configurationproperties Annotations Support batch injection, while value annotations are suitable for single injection;

Second, configurationproperties annotations support data validation, and value annotations are not supported;

Configurationproperties annotations support loosely matching attributes, while value annotations must match attributes strictly;

Iv. Configurationproperties does not support powerful spel expressions, and value supports;

Iv. configuration file placeholders

Placeholders and random numbers are relatively simple, and the code is posted directly here. It is important to note that:

The value of the placeholder must be the full path

Placeholder set default value, no space after colon

ran:  # 这里的prefix不能是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:此处不能有空格,且key为完整路径}
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/*** random number and placeholder syntax classes */@Component@ConfigurationProperties(prefix ="ran") Public classrandomentity {PrivateString Ranvalue;//randomly generate a string    PrivateInteger Ranint;//Randomly generate an integer    PrivateLong Ranlong;//Randomly generate a long integer    PrivateInteger Ranintnum;//randomly generate an integer within the specified range    PrivateInteger Ranintrange;//randomly generate an integer within the specified interval    PrivateString Ranplaceholder;//Placeholder    //Omit Getter,setter,tostring method E}

Test code:

@RunWith(Springrunner.class)@SpringBootTest Public classspringbootymlapplicationtests {@Autowired    PrivateUserInfo UserInfo;@Autowired    PrivateYamlentity yamlentity;@Autowired    PrivateConfigurationpropertiesentity configurationpropertiesentity;@Autowired    PrivateValueentity valueentity;@Autowired    PrivateRandomentity 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); }}
V. Summary

Spring Boot supports two format profiles, where Yaml's data structure is clearer than properties.

Two, YAML is dedicated to write the language of the configuration file, very concise and powerful.

Three, YAML requirements for space is very strict, and can not be replaced by the TAB key.

D. YAML determines the level by the amount of space indentation, followed by a space after the colon, and a space behind the dash.

V. configurationproperties annotations suitable for bulk injection of properties in a configuration file, the value annotation is suitable for obtaining an item in the configuration file.

VI. configurationproperties annotations Support data validation and get complex data, and value annotations support Spel expressions.

The article ends here. If the article is helpful to you, you can order a " recommendation ", you can also " follow " me, get more rich knowledge.

Here is part of the list of blog posts in the table of contents, if you have interesting content can click on the right link: http://www.cnblogs.com/itdragon/p/8709948.html

The Spring Boot configuration file is detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.