This is the third article, a summary of YAML configuration files
Interested friends can go to know about the other several articles have been published, your praise is the biggest support for me, thank you!
Interested friends can go to know about the other several articles have been published, your praise is the biggest support for me, thank you!
- The article directories
SpringBoot takeoff road -HelloWorld
(two) SpringBoot takeoff road – analysis of the principle of entry
(three) SpringBoot takeoff road -YAML configuration summary (entry must know will)
(4) SpringBoot takeoff road – static resource processing
(five) SpringBoot takeoff road -Thymeleaf template engine
(6) SpringBoot takeoff road – integration jdbctemplate-druid-mybatis
(7) SpringBoot launch road – integration of SpringSecurity (Mybatis, JDBC, memory)
(eight) SpringBoot take-off path – integration Shiro detailed tutorial (MyBatis, Thymeleaf)
SpringBoot -Swagger 2 And 3
Description:
- SpringBoot takeoff road series of articles involved in the source code, are synchronized to github, there is a need for small partners, go down at will
- Github.com/ideal-20/Sp…
- Untalented and uneducated, will point to shallow knowledge, we should be a tool to see it, do not like to spray ha ~
(1) SpringBoot configuration file type
In the previous introduction to the Basics, we briefly mentioned some instructions for automatic configuration, and when we demonstrated this, You can easily change the port number by simply writing server.port=9090 to application.properties under SRC \main\ Resources
Properties or Application.yml (application.yaml) configuration if you want to modify SpringBoot
Properties, which we are relatively familiar with, were used a lot in Spring development in the past
This article focuses on the yamL genre
(2) Introduction to YAML
Wikipedia post introduction
YAML is a recursive abbreviation of “YAML Ain’t a Markup Language” (YAML is not a Markup Language). At the time the Language was developed, YAML actually meant “Yet Another Markup Language” (still a Markup Language), but was renamed with a reverse acronym to emphasize the Language’s data-centric, rather than Markup language-centric focus.
Features of wikipedia posts
YAM’s syntax is similar to that of other high-level languages, and it can simply express manifest, hash, scalars, and other data forms. It uses whitespace indentation and a lot of look-and-feel features, making it especially suitable for expressing or editing data structures, various configuration files, printing debugging content, and file size. Although it is more suitable for expressing hierarchical data structures, it also has a sophisticated syntax for expressing relational data. Its most user-friendly feature is the clever avoidance of closed symbols, such as quotation marks and various brackets, which can become complicated and difficult to read in nested structures
Let’s start with an example:
- The XML configuration
<server>
<port>9090<port>
</server>
Copy the code
- The Properties configuration
server.port=9090
Copy the code
- Yaml configuration
Server:
prot: 9090
Copy the code
From such a simple example, Properties and Yaml are relatively simple, at least compared to XML, and XML is a nightmare when it comes to complex lists and so on
So, a quick summary: YAML language files, which have a. Yml suffix, are more readable and concise than XML (mainly) or Properties, and are more data-centric than markup language, making them suitable as configuration files for development projects
(3) Basic grammar
(1) Grammar requirements
-
The space between value and colon cannot be omitted, for example, key: value, ‘:’ can be followed by a space
-
The indentation indicates the hierarchy, and the data in the left-aligned column is of the same hierarchy
-
You can’t indent with tabs, you can only indent with blank Spaces
-
Syntax is case sensitive
(2) Configure common data
Ordinary data here is worth: numbers, booleans, strings, etc
Grammar:
key: value
Copy the code
Example:
name: ideal
Copy the code
-
Normal data values are written directly after colons (followed by Spaces), and usually strings do not require single or double quotation marks
-
The “” double quote returns an escape character such as” \n “as a newline character
-
‘ ‘single quotes do not parse escapes, and ‘\n’ is returned as a string
(3) Configure object data and Map data
Grammar:
- Basic writing
key:
key1: value1
key2: value2
Copy the code
- Inline writing
key: {key1: value1.key2: value2}
Copy the code
Example:
user:
name: Steven
age:20
address: beijing
Copy the code
user: {name:Steven.age: 20.address: beijing}
Copy the code
Note: the number of Spaces in front of key1 is not limited, although the default is two, but as long as it is the same indentation, on behalf of the same level, the default can be used, that’s all
(4) Configure array, List and Set data
There is a space between – and value1, etc
Grammar:
- Basic writing
key:
- value1
- value2
Copy the code
- Inline writing
key: [value1.value2]
Copy the code
Example:
province:
- guangdong
- hebei
- sichuan
Copy the code
province: [guangdong.hebei.sichuan]
Copy the code
Add: When the elements in the collection are objects, as shown in the following example
user:
- name: zhangsan
age: 20
address: beijing
- name: lisi
age: 28
address: shanghai
- name: wangwu
age: 26
address: shenzhen
Copy the code
(4) Attribute mapping between configuration files and configuration classes
(1) @ Value mapping
In Spring, we’ve already introduced the @Value annotation, which allows you to map values in a configuration file to fields in a Spring-managed Bean
To demonstrate this, create a simple User class with just three members
@Component
public class User {
private String name;
private Integer age;
privateString address; . Add get, toString method (set can not write)}Copy the code
The tests are all uniform
@Controller
public class UserController {
@Autowired
User user;
@RequestMapping("/testUser")
@ResponseBody
public String testUser(a){
returnuser.toString(); }}Copy the code
Now let’s do it in three ways
A: Direct assignment
@Value("Tom")
private String name;
@Value("20")
private Integer age;
@ Value (" Beijing ")
private String address;
Copy the code
B: the Properties
application.properties
user1.name=Jack
user1.age=30
user1.address=Beijing
Copy the code
User
@Value("${user1.name}")
private String name;
@Value("${user1.age}")
private Integer age;
@Value("${user1.address}")
private String address;
Copy the code
C: Yaml
application.yml
user1:
name: Steven
age: 20
address: Beijing
Copy the code
User
@Value("${user1.name}")
private String name;
@Value("${user1.age}")
private Integer age;
@Value("${user1.address}")
private String address;
Copy the code
Take a look at the yamL test results
D:
1 configuration priority
Properties, YAMl, and YML configuration files, if configured at the same time, the configuration information in the three files will take effect, but there is a loading priority problem, and the last loaded file will overwrite the first loaded file. Yml > YAMl >properties is the last file to be loaded, so the priority is :properties> YAMl > yML.
② User naming problem
@value (“${user1.name}”) I used user1 because if user.name is used in Windows, it will get the user name of the current Windows user
(3) application
Properties or application.yaml or application.yml, because the default is to find these configuration files. If the configuration file is named incorrectly, it will not be found
④ Properties garbled characters
If you did not set before, Chinese will certainly be garbled, here is a supplement to set the method
Check the box below and set the Properties encoding to UTF-8
(2) @ ConfigurationProperties mapping
The entity class uses the @ConfigurationProperties annotation (prefix=” prefix of key in the configuration file “), which automatically maps the configuration in the configuration file to the entity
Note: there may be some errors, generally no impact, the solution is placed below the article, if no impact, just do it first
A: Configure the entity class
At sign Value, if you have a lot of members, it’s a little bit more convenient to introduce one, and it’s going to be used a lot in the future, so I’m going to rewrite a little bit more complicated entity, and I’m going to show you a little bit more comprehensively
Note: To implement this using @ConfigurationProperties, you add a set method to its member, which you can do without using the @Value annotation
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
private String name;
private Integer age;
private Date birthday;
private Boolean graduate;
private Map<String, Integer> score;
private List<String> subject;
privateUser u; . Get set toStringCopy the code
The User class referenced in the Student class
@Component
public class User {
private String name;
private Integer age;
privateString address; . Get set toStringCopy the code
B: YAML configuration
student:
name: Steven
age: 20
birthday: 2020/ 01/01
graduate: false
score: {math: 90.english: 88}
subject:
- The high number of
- The British
- Big things
u:
name: Jack
age: 30
address: Beijing
Copy the code
(3) Load the specified properties profile
Add one more tip about loading the specified properties configuration file
Spring uses yML configuration by default, but sometimes uses traditional XML or properties configuration. By the way, what if you want to invoke a custom properties configuration?
Use the @propertysource annotation
@Component
@PropertySource(value = "classpath:user.properties")
@ConfigurationProperties(prefix = "usertest")
public class User {
private String name;
private Integer age;
privateString address; . Get set toStringCopy the code
user.properties
usertest.name=Jack
usertest.age=30
usertest.address=Beijing
Copy the code
(v) Solutions
1. Spring Boot Configuration Annotation Processor not found in classpath error
IDEA prompt, springboot configuration annotation processor is not found, it will give us the address, let us go to see the document, but some documents are not necessarily open, you can go to the official website to find a
Take a look at the instructions on the official website
Generating Your Own Metadata by Using the Annotation Processor
You can easily generate your own configuration metadata file from items annotated with @ConfigurationProperties by using the spring-boot-configuration-processor jar. The jar includes a Java annotation processor which is invoked as your project is compiled. To use the processor, include a dependency on spring-boot-configuration-processor.
With Maven the dependency should be declared as optional, as shown in the following example:
So it’s ok to add dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
Copy the code
2. Re-run Spring Boot Configuration Annotation Processor to update generated metadata
This problem can be ignored and does not affect the code execution. It should only be a reminder to remind you to restart or recompile if necessary. I have not found a perfect solution to this problem.
- Under Setting, search for Spring, find SpringBoot and deselect show Notification Panel
(six) doubt occupied building
For spring-boot-configuration-processor, some say it was used to introduce @propertysource, and some say it was used to enable @ConfigurationProperties
@Component
@PropertySource(value = "classpath:user.properties")
@ConfigurationProperties(prefix = "usertest")
public class User {
private String name;
private Integer age;
privateString address; . Get set toStringCopy the code
However, if you test it, you can use these two annotations without introducing spring-boot-configuration-processor. I haven’t thought about them carefully and ignored them. If you know about them, you can leave a message and communicate with them
(7) Ending
If there is any deficiency in the article, you are welcome to leave a message to exchange, thank friends for their support!
If it helps you, follow me! If you prefer the way of reading articles on wechat, you can follow my official account
We don’t know each other here, but we are working hard for our dreams
A adhere to push original development of technical articles of the public number: ideal more than two days