Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities
preface
To better enable Spring Boot to generate configuration metadata files, you can add the Spring Configuartion Processor dependency when you create your project, or manually add it in the pom.xml file after you create your project. By adding this dependency, we can write configurations with property prompts, greatly reducing coding errors.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
Copy the code
application.properties
Custom attributes
The application. Properties configuration file comes with the project after it is created. If you want to customize the properties, you can configure them directly in the file as follows:
- in
application.properties
To add the configuration we want to customize;
cunyu.id=1024
cunyu.name=Village, the rain away
cunyu.website=https://cunyu1943.github.io
Copy the code
- Create entity classes to map our configured properties;
package com.cunyu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/ * * *@author : cunyu
* @version : 1.0
* @className : CunyuProperties
* @date: 2020/7/29 "*@description : TODO
*/
@Component
@ConfigurationProperties(prefix = "cunyu")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CunyuProperties {
private int id;
private String name;
private String website;
}
Copy the code
- Define Controller to inject tests;
package com.cunyu.controller;
import com.cunyu.pojo.CunyuProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/ * * *@author : cunyu
* @version : 1.0
* @className : CunyuPropertiesController
* @date : 2020/7/29 13:37
* @description : TODO
*/
@RestController
@RequestMapping("/cunyu")
public class CunyuPropertiesController {
private static final Logger logger = LoggerFactory.getLogger(CunyuPropertiesController.class);
@Autowired
CunyuProperties cunyuProperties;
@GetMapping("/profile")
public String cunyuProfile(a){
logger.info("-- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
logger.info(cunyuProperties.toString());
logger.info("-- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
returncunyuProperties.toString(); }}Copy the code
- Open the web page test, open 1, and observe the console. If the following information is displayed, the property injection is successful.
Multi-environment Configuration
In the actual development process, multiple environments (such as development, testing, and production) are often required, and the configurations of different environments are different. In this case, the configuration method is as follows.
- Create configuration files for different environments. The configuration files are named
application-{profile}.properties
.{profile}
Customize the environment for us as follows:
Development environment: application-dev.properties
server.servlet.context-path=/dev
Copy the code
Test environment: application-test.properties
server.servlet.context-path=/test
Copy the code
Production environment: application-prod.properties
server.servlet.context-path=/prod
Copy the code
- Then, in
application.properties
To add the active environment, the configuration of the corresponding environment will be activated.
# {profile} corresponds to dev, test, prod above
spring.profiles.active={profile}
Copy the code
The reason to divide the configuration into multiple environments is mainly to facilitate the development requirements in different environments. For example, if we want to develop new functions, we can activate the relevant Settings of the development configuration file at this time, wait for the completion of development, and then switch to the test environment for testing. After rigorous testing, we were able to put new features into production. Throughout the development process, we not only completed the development of new functions, but also did not affect the use of the existing system, so now everyone is basically based on this model for business development.
Custom configuration files
If we don’t want to use the application. Properties configuration environment that comes with the project, we can also customize the configuration we need. But how do you configure it? Let’s take a look at ~
- Start by creating a custom profile
my.properties
, the file name can be customized, but the suffix should keep the same, and then add the attributes of our customized configuration;
my.id=1024
my.name=Village, the rain away
my.website=https://cunyu1943.github.io
Copy the code
- Define entity classes for mapping content in custom profiles;
package com.cunyu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/ * * *@author : cunyu
* @version : 1.0
* @className : MyProperties
* @date : 2020/7/29 14:05
* @description : TODO
*/
@Component
@PropertySource("classpath:my.properties")
@ConfigurationProperties(prefix = "my")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MyProperties {
private int id;
private String name;
private String website;
}
Copy the code
- Define controllers to inject tests
package com.cunyu.controller;
import com.cunyu.pojo.MyProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/ * * *@author : cunyu
* @version : 1.0
* @className : MyPropertiesController
* @date : 2020/7/29 14:07
* @description : TODO
*/
@RestController
@RequestMapping("/my")
public class MyPropertiesController {
private static final Logger logger = LoggerFactory.getLogger(MyPropertiesController.class);
@Autowired
MyProperties myProperties;
@GetMapping("/profile")
public String myProfile(a) {
logger.info("= = = = = = = = = = = = =");
logger.info(myProperties.toString());
logger.info("= = = = = = = = = = = = =");
returnmyProperties.toString(); }}Copy the code
- Open web test, open
http://localhost:8080/my/profile
And observe the console. If the following information is displayed, the property is successfully injected.
Pay attention to
Properties and my.properties will load application.properties first.
, yml and properties
In general, when you create a Spring Boot project using IDEA, an application.properties configuration file is generated by default. This configuration file is used to change the default values for Spring Boot automatic configuration. However, some people prefer to use application.yml, so the question is, what is the difference between the two formats?
Before we start the comparison, let’s take a look at each example:
- The format
server.port=8081
spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
spring.datasource.url=jdbc:mysql://aliyuncs.com:3306/database?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true
spring.datasource.username=root
spring.datasource.password=* * * * * *
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
Copy the code
- . Format of yml
server:
port: 8082
spring:
datasource:
name: test
url: JDBC: mysql: / / 127.0.0.1:3306 / database
username: root
password: * * * * * *
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
Copy the code
From the above example, we can find that the differences between the two are mainly as follows:
- Grammatical structure
-
The. Properties format uses key=value, while the. Yml format uses a tree structure.
-
The. Properties format is connected by a. And =, which is structurally more direct, while the. Yml format is hierarchical with:, which presents a tree structure, and the assignment must be followed by a space
- Order of execution
If both formats exist in a project, the.yml file will be loaded first, followed by.properties, and the later-loaded.properties file will overwrite the previously loaded.yml file.
In addition, note the following when configuring.yml:
- Indent must be space, not Tab
@PropertySource
Comments cannot be loadedyml
file
conclusion
That’s all about configuration in Spring Boot. This article focuses on information about the configuration files that come with the Spring Boot project, as well as how to customize the configuration if you want to meet your needs. Finally, it explains the differences between.yml and.properties configuration files in different formats.