Article Catalog
1. Role of configuration files
All important data in a SpringBoot project is configured in configuration files, such as.
- Connection information for the database (including user name and password settings);
- The startup port for the project;
- Information such as the invocation secret key of the third-party system;
- General and exception logs for discovering and locating problems;
- Configuration can also be customized, such as configuring information about where to save uploaded files.
Imagine if there is no configuration information, then the Spring Boot project can not connect and manipulate the database, and even the key logs that can be used to troubleshoot the problem can not be saved, so the role of the configuration file is very important.
There are two types of configuration types in the configuration file.System Configuration Items, the format of such configurations are fixed and are given to the system (framework); the other is theUser-defined configurationThe user can specify the format of the configuration items, and the user can set and read them by himself/herself.
2. Configuration file format
There are two types of SpringBoot project configuration files, one is the one that comes with the project by default.properties
file, there is also a relatively newyml
file (you need to add it yourself).
The configuration file is present in theresources
directory, for the SpringBoot project’s default configuration file, the name of the configuration file must beapplication
namelyapplication.properties
orapplication.yml
file, if the configuration file name is notapplication
Then it won’t be able to be recognized for loading.
properties
It’s possible to work withyml
existed together in a project.yml
The file is a bit more complex than theproperties
The file has some optimizations, such asyml
file naturally supports Chinese characters, and theproperties
The file does not support Chinese characters by default, if you do not configure the characters, the input of Chinese characters will be garbled.
whenapplication.properties
andapplication.yml
When two files coexist, although the configuration in both files will be loaded, if the same configuration appears in both configuration files (e.g., “server.port” is configured in both properties and yml), the configuration file will be loaded asproperties
The configuration in the main, that is, the.properties
Configure the file with the highest priority.
Although .properties can theoretically coexist with .yml, in practice we usually adopt a unified configuration file format for better maintenance (and lower failure rates).
3. Configuration file usage
The properties configuration file is the earliest configuration file format and is the default configuration file used to create Spring Boot projects.
3.1. properties configuration file
3.1.1 Basic syntax and usage
Basic Grammar:
Properties are configured as keys and values, with “=” connecting the key to the value, and “#” being used to add comments.
# Don't put a space between key and = and value.
key=value
For example, to set the port number, we can use the configuration itemserver.port
to set the port:
server.port=8088
After the configuration is modified, start the program and you will see that the port number has been set to the port number set in the configuration file.
There is also, for example, setting up the database with the following configuration items:
# Configure the database URL
spring.datasource.url="jdbc:mysql://127.0.0.1:3306/tr?characterEncoding=utf8&useSSL=false"
# Configure the database username
spring.datasource.name="root"
# Configure the database password
spring.datasource.password="111111"
# Setting up the driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
For more information on configuring the system, check out the official documentation:https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#appendix.application-properties
In addition to setting the information in the configuration file In addition to the system configuration, we can also customize the configuration, for example:
# User-defined configuration
custom.name=zhangsan
custom.id=666
To read the information in the configuration file at this point, we can use the@Value
annotation to implement it, the rules are as follows:
// Note that ${} cannot be omitted.
@Value("${Configuration info key}")
private String name;
Sample code:
package com.example.springboot.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ResponseBody
public class TestController2 {
// Both custom and system configurations can be read.
@Value("${custom.name}")
private String name;
@Value("${custom.id}")
private String id;
@Value("${server.port}")
private String port;
@RequestMapping("/coustom")
public String sayHi() {
return "name : " + name + " "
+ "id : " + id + " "
+ "port : " + port;
}
}
Browser access results:
3.1.2 Analysis of the advantages and disadvantages of properties
Pros:
- Configuration file structure is clear: key=value, not easy to error, suitable for beginners.
Drawbacks:
- The writing style is redundant and bloated. yml configuration files can solve this problem.
3.2. yml configuration file
yml stands for YMAL (Yet Another Markup language) and translates toalternative markup language (XML)。
3.2.1 Basic syntax and usage
Basic Grammar:
yml is a tree structure configuration file, especially need to pay attention to the key and value between the need to use the English colon plus space, space must not be omitted.
# :space must not be omitted
key: value
At this point, the top of thepropertise
convertyml
Format to look at.
# Configure the port
server:
port: 8088
# Configure the database
spring:
datasource:
url: "jdbc:mysql://127.0.0.1:3306/tr?characterEncoding=utf8&useSSL=false"
username: "root"
password: "111111"
# Customized configuration information
custom:
name: zhangsan
id: 666
The yml configuration file is read in the same way as the properties configuration file, so I won’t demonstrate it again.
3.2.2. single and double quote problems in yml
Let’s try to set the configuration information in the configuration file to the following words:
string:
str1: Hello \n Spring Boot.
str2: 'Hello \n Spring Boot.'
str3: "Hello \n Spring Boot."
We inject this configuration information into a class, and we try to read it. This code @Controller injects a YmlString object into the framework at Spring Boot startup, and when it does so, it executes the @PostConstruct initialization method, which is what reads the configuration information at this point.
@Controller
public class YmlString {
@Value("${string.str1}")
private String str1;
@Value("${string.str2}")
private String str2;
@Value("${string.str3}")
private String str3;
@PostConstruct
public void postConstruct() {
System.out.println("string.str1:" + str1);
System.out.println("string.str2:" + str2);
System.out.println("string.str3:" + str3);
}
}
The console outputs the results:
This means that values wrapped in double quotes are executed according to the original semantics, while values wrapped in single quotes (special characters) are escaped, as in the example above which is\n
is escaped into\\n
So it outputs\n
, which ends up being just a regular string.
As for the output result without double quotes is because strings in yml are not quoted by default, they are just output directly.
3.2.3. yml configuration of different types of data types and null
The format is as follows:
# String
string.value: Hello
# Boolean, true or false
boolean.value: true
boolean.value1: false
# Integer
int.value: 10
int.value1: 0b1010_0111_0100_1010_1110 # Second division
# Floating point
float.value: 3.14159
float.value1: 314159e-5 # scientific notation
# Null, ~representative null
null.value: ~
Use:
package com.example.springboot.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class TestController3 {
@Value("${string.value}")
private String str;
@Value("${boolean.value}")
private boolean bool;
@Value("${float.value}")
private float flo;
@Value("${null.value}")
private Integer nul;
@PostConstruct
public void postConsrtuct() {
System.out.println("str: " + str);
System.out.println("bool: " + bool);
System.out.println("flo: " + flo);
System.out.println("nul: " + nul);
}
}
Run results:
3.2.4 Configuration objects
For ym l configuration files, it is also possible to do object configuration, such as setting up aStudent
Object:
Way 1:
student:
id: 1
name: Beta
age: 18
Way 2:
student: {id: 1,name: Zhang SAN,age: 18}
Instead of using the @Value annotation to read the customized object from the configuration file, you need to use the@ConfigurationProperties
annotation for object reading, and the corresponding class must have thegetter and setter
Methods.
Example:
Student category:
We don’t write our own here.getter and setter
Instead, we use the @Data annotation from the Lombok framework, which includes get, set, and toString, eliminating the need to create them manually.
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@ConfigurationProperties(prefix = "student")
@Component
public class Student {
private int id;
private String name;
private int age;
}
Use class:
package com.example.springboot.controller;
import com.example.springboot.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javax.annotation.PostConstruct;
@Controller
public class ConfigController {
@Autowired
private Student student;
@PostConstruct
public void postConsrtuct() {
System.out.println(student);
}
}
Run results:
3.2.5. Placement set
yml can also configure collections
For example, to configure a list collection, configure it as follows:
Way 1:
dbtypes:
name:
- mysql
- sqlserver
- db2
Mode 2 (recommended):
dbtypes: {name: [mysql, sqlserver, db2]}
Getting is exactly the same as getting an object, except that now you need a property inside the class to be a collection object.
Get examples:
The object corresponding to the configuration file.
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Data
@ConfigurationProperties(prefix = "dbtypes")
@Component
public class ConfigList {
private List<String> name;
}
Use class:
package com.example.springboot.controller;
import com.example.springboot.model.ConfigList;
import org.springframework.stereotype.Controller;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
@Controller
public class ConfigController {
@Resource
private ConfigList configList;
@PostConstruct
public void postConstruct() {
System.out.println(configList.getName());
}
}
Run results:
Another example is configuring a map collection, which is configured as follows:
Way 1:
tes:
map:
1: The Calendar
2: Li Si
Way 2:
tes:
maps: {1: Zhang SAN,2: Li Si}
Get examples:
The object corresponding to the configuration file:
package com.example.springboot.model;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Map;
@Data
@ConfigurationProperties(prefix = "tes")
@Component
public class ConfigMap {
private Map<Integer, String> map;
}
Use class:
package com.example.springboot.controller;
import com.example.springboot.model.ConfigMap;
import org.springframework.stereotype.Controller;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
@Controller
public class ConfigController2 {
@Resource
private ConfigMap configMap;
@PostConstruct
public void postConstruct() {
System.out.println(configMap.toString());
}
}
Run results:
3.2.6. yml Benefits Analysis
- yml is a highly readable, simple to write, easy to understand language with a syntax similar to that of the JSON language.
- yml supports more data types, it can simply express lists (arrays), hash tables, scalars and other data forms.
- It is particularly suitable for expressing or editing data structures, various configuration files, and so on, using indentation in white space symbols and a number of appearance-dependent colors.
- yml supports more programming languages than Java and can be used in Golang, PHP, Python, Ruby, JavaScript, Perl, and more.
4. The difference between properties and yml
- The syntax is different: properties is a key-value configuration file in the form of key = value, whereas yml uses a tree configuration similar to the json format, with newline indentation between yml levels, and a colon between key and value.
:
The space cannot be omitted. - properties is the early and default configuration file format, but the configuration has some redundant data, using yml can be a good solution to the data redundancy problem.
- yml is more generic and supports more languages, such as Java, Go, Python. For cloud server development, you can use a single yml configuration file as a common configuration file for Java and Go.
- yml and properties can coexist, but it is recommended to use a unified configuration type file within a project.
- yml supports more data types than properties, such as objects and collections.
5. Setting up configuration files for different environments
In daily development, it is common to use at least three different environments: the development environment (dev), the test environment (test) and the production environment (prod); the configuration of each environment is different, including the database, ports, IP addresses and other information; so how to distinguish between these environments and how to package them?
Spring Boot provides good multi-environment integration support, you can freely switch between different environments at packaging and runtime.
In order to facilitate the management of the configuration of different environments, you can put them in different configuration files, at this time we need to create configuration files for different environments, for exampleapplication-dev.properties
、application-test.properties
andapplication-prod.properties
。
It is important to note that the naming of configuration files must follow theapplication-name.properties
orapplication-name.yml
format, where thename
Can be customized for differentiating between different environments.
Therefore, four configuration files are required throughout the project, includingapplication.properties
(the main configuration file, which is required to be present) and three configuration files for different environments.
At this point, after creating the configuration files for each environment, you also need to tell SpringBoot which environment you want to run, and there are two main ways to specify this.
Way 1: Specify in the main configuration file
This can be done in the main configuration file (application.properties
orapplication.yml
) is specified in the following:
# Specify the runtime environment as a test environment (application.properties)
spring.profiles.active=test
# Specify the runtime environment as production (application.xml)
spring:
profiles:
active: pord
At this point, SpringBoot will first load theapplication.properties
file, which in turn tells SpringBoot to find the configuration file for the specified environment.
Way 2: When running the jar, specify
SpringBoot’s built-in environment switching can be used to switch the environment when running theJar
package to specify the environment with the following command:
java -jar xxx.jar --spring.profiles.active=test