头图
In the previous chapter, we talked about the yml configuration file. Do you still remember? It's easy to use, but there will be many problems in actual production.
  1. Testing is a set of configuration, and production is a set of configuration; different people develop different modules and sharing a yml file is prone to conflicts;
  2. Local development requires localized configuration and debugging. In this section, we will solve all these headaches.
First, we create a project and change the suffix of the application.properties application.yml .
name: 张三
lesson: springboot
desc: ${name}同学正在努力学习${lesson}!!! #占位符

DemoController.java

@RestController
@RequestMapping("demo")
public class DemoController {

    @Resource
    private YmlData ymlData;

    @GetMapping("test")
    public void test() throws JsonProcessingException {
        System.out.println(ymlData.getDesc());
    }
}

YmlData.java

@Data
@Component
public class YmlData {

    @Value("${name}")
    private String name;
    @Value("${lesson}")
    private String lesson;
    @Value("${desc}")
    private String desc;
}
Browser request http://localhost:8080/demo/test look at the console, garbled characters

Set the encoding format, ide-->file-->setting-->editor-->file encodings

After the setting is complete, application.yml completely garbled, re-enter, restart after changing, and request again, the console output:

张三正在努力学习springboot!!!

What does this have to do with multi-environment configuration?

Well, it’s okay, but you learned one more yml file placeholder, and our following example will also be changed based on this.

application-prod.yml

name: 张三prod
lesson: springboot
desc: ${name}正在努力学习${lesson}!!!

application-dev.yml

name: 张三dev
lesson: springboot
desc: ${name}正在努力学习${lesson}!!!

application.yml

spring:
  profiles:
    active: dev #多环境变量的精髓,这里确定是加载哪个配置文件!!!

Okay, now restart, after executing a request, what is the console output?

张三dev正在努力学习springboot!!!

Can I choose which configuration file to load when debugging? , Operate as shown in the figure below

Restart and see what is printed now? Yes printed

张三prod正在努力学习springboot!!!

Add another application-test.yml

name: 张三test

Modify application.yml as follows:

spring:
  profiles:
    include: test,prod #包含哪些配置
    active: dev #多环境变量的精髓,这里确定是加载哪个配置文件!!!

Restart the project and see what is printed?

张三prod正在努力学习springboot!!!

From the results, we can see that the configuration including the include is included, and the last one used in the included file for the same configuration takes effect.

And even if the active file has the same configuration (name configuration in this article), it is not overwritten. In addition, the configuration that is not included in the configuration file included in the include will be added to the active.

In summary: include and active take the union, the same configuration is subject to the last one in include!

More java original reading: https://javawu.com


大盛玩java
24 声望5 粉丝