Spring Boot configuration file
Spring Boot uses a global configuration file, application.properties, or yML format, in the Resources directory by default. Specified by the code specified in the configuration file for “classpath: application. The properties”. The default configuration file for creating a Spring Boot project with IDEA is in the properties format.
The global configuration file for Spring Boot allows you to modify the default configuration.
2. YMAL configuration file
Create a spring-boot-Configuration project, import the basic Web and Lombok dependencies, and change the application.properties configuration file to application.yml. Create the Entity package and add the Person and Dog entity classes
@Data
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> list;
private Dog dog;
}
Copy the code
@Data
public class Dog {
private String name;
private Integer age;
}
Copy the code
2.1 – YAML Configuration file basic syntax
YAML basic syntax
The basic syntax rules of YAML are as follows:
- Use indentation to indicate hierarchy
- The Tab key is not allowed for indentation. Only Spaces are allowed
- The number of Spaces indented does not matter, as long as the elements of the same rank are to the left of them
- Case sensitivity
YAML supports the following data structures:
- Object: a collection of key-value pairs
- Array: A set of values arranged in order
- Literals: A single, indivisible value
The YAML format is K: V, which represents a pair of key-value pairs (colons must be followed by Spaces). The hierarchy is controlled by indented Spaces. All aligned columns are considered to be at the same level. For example, configure application access ports in YML
server:
port: 8081
path: /
Copy the code
The hierarchy is represented by indentation. Path and port are at the same level, and properties and values in YML files are case sensitive.
Data types supported in the YAML configuration file
Literals: Common values, including numbers, strings, and Booleans (true and false) in key: value format. Literal values are written directly. Single or double quotation marks are not used in strings by default. There is a difference between single and double quotes in YML configuration files
- “” : double quotes do not escape special characters. Special characters act as their intended function.
- For example, name: “zhangsan\nlisi”, output three newline lisi
- “: Single quotes escape strings, special strings end up just plain string data
- For example, name: ‘zhangsan \n lisi’, zhangsan \n lisi is output
The format of the object and Map(attribute and value/key-value pair) is key: value. Write the attribute name and value in k: V on the next line of the object name. The format of the specific attribute name and value of the object is still K: V
friend: # object name
The # object contains the name and value of the property
lastName: zhangsan # Attribute name: attribute value
age: 30
Copy the code
Another way to write it is inline, using {} to include the attribute name and k: v of the attribute value.
friend:{lastName: zhangsan, age: 18}
Copy the code
Array (List, Set), using -value to denote an element in the array
# Array or collection name
pets:
# The elements contained in the collection
- cat
- dog
- pig
Copy the code
You can also use [], and separate values with commas (,)
pets: [cat.dog.pig]
Copy the code
Composite structures, including objects, arrays, strings and other forms of data
Assign values to the Person object properties using the YML configuration file
Rename the application.properties file in the Resources directory to application.yml, use yML to assign a value to the Person object, and import a configuration file to handle dependencies. IDEA will be prompted when writing the configuration file
<! -- Import configuration file handler -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
Copy the code
The content of the application.yml configuration file is
# object name
person:
# Attribute name: attribute value
lastN-name: stark
age: 40
boss: true
birth: 1970/ 12/12
maps: {k1: v1.k2: v2}
list:
- l1
- l2
- l3
- l4
dog:
name: pipi
age: 2
Copy the code
The @ConfigurationProperties annotation needs to be used in the Person object that maps property values from the YML configuration file, This annotation binds the annotation class to the configuration specified in the annotation (the default specified configuration file is application.yml). The prefix attribute in the annotation represents the configured prefix and maps the configuration under this prefix to the attributes in the Person object
You also need to add the class to the Spring container using the @Component annotation, and you must be a Component in the container to use the @ConfigurationProperties annotation to get the Person object from the container and output it to see if the assignment was successful
Add annotations to the Person entity class
@ConfigurationProperties(prefix = "person")
@Component
@Data
public class Person {
// The middle content remains unchanged
}
Copy the code
Add the test class PersonTest under the Test package
@SpringBootTest
public class PersonTest {
@Autowired
private Person person;
@Test
public void testPerson(a){ System.out.println(person); }}Copy the code
Perform the testThe console prints the Person object, and the property is successfully assigned
Assign values to objects using the properties file configuration
person.last-name=stark1
person.age=19
person.birth=1980/12/12
person.boss=true
person.maps.k1=v1
person.maps.k2=v2
person.list=a,b,c
person.dog.name=pipi
person.dog.age=2
Copy the code
Annotate the configuration in the YML file and perform the testsYou can also successfully assign a value to a property of Person.
When configuration files in both yML and Properties formats exist at the same time, yML format has a higher priority
Assign values to attributes using the @value annotation
In addition to the @ConfigurationProperties annotation to specify configuration prefixes for assignment, you can also use the @Value annotation to specify configuration and property-by-property bindings. The @value annotation serves the same purpose as the Value attribute of property under the bean tag in the Spring XML configuration file, which is used to assign values to properties.
Use the @Value annotation on the entity class attribute in Person
//@ConfigurationProperties(prefix = "person")
@Component
@Data
public class Person {
@Value("${person.last-name}")
private String lastName;
@Value("#{10*2}")
private Integer age;
@Value("true")
private Boolean boss;
// Leave the rest unchanged
}
Copy the code
Change the content of the application.yml configuration file to
person:
last-name: stark
Copy the code
Execute the PersonTest testIt is also possible to bind the lastName attribute of the Person entity class successfully to the configuration in the configuration file, and some expressions are supported based on the output @value.
@Value supports fetching only primitive type data, using the @Value annotation on the MAPS attribute of the Person entity class to retrieve data from the configuration file
@Value("${person.maps}")
private Map<String,Object> maps;
Copy the code
Modify the application.yml configuration file
#...
maps: {k1: v1.k2: v2}
list:
- l1
- l2
- l3
- l4
dog:
name: pipi
age: 2
Copy the code
Perform the test
The Maps property of the Person object failed to be assigned.
@Value VS @ConfigurationProperties
@ ConfigurationProperties | @ the Value | |
---|---|---|
function | Batch injection of property values in configuration files | Specify the corresponding values of the attributes one by one |
Loosely bound syntax | support | Does not support |
SpEL expression | Does not support | support |
JSR303 data verification | support | Does not support |
Complex type encapsulation | support | Does not support |
Loose binding does not support testing
person:
last-name: stark
Copy the code
@Value("${person.lastName}")
private String lastName;
Copy the code
Perform the test${person.lastName} in @value (“${person.lastname}”) cannot be bound to person.last-name in the configuration file
Plus: Attribute name matching rule. Take the lastName attribute of the Person entity class as an example. It can be written in the following forms in the configuration file
- Person.lastname: Consistent with the property name
- Person.last-name: Use the – connection and change the uppercase to lowercase
- Person. last_name: Use _ connection and change the first letter from uppercase to lowercase
Data verification does not support testing
Validation Starter no longer included in Web Staters after Spring Boot version 2.3. If you need validation, import the following dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Copy the code
How to choose between @Value and @ConfigurationProperties?
You are advised to use @Value if you only want to obtain the Value of a configuration file in the business logic. You are advised to use @ConfigurationProperties if an entity class is mapped to the configuration file
A simple example of using @value annotations
Increase the HelloController
@RestController
public class HelloController {
@Value("${person.last-name}")
private String name;
@RequestMapping("/hi")
public String hi(a){
return "Hi, "+ name; }}Copy the code
Restarting an application