SpringBoot - 高级特性
本节学习SpringBoot原理解析和SpringBoot的一些高级特性。
1. Profile功能
由于开发环境、测试环境和生产环境的配置都不一样,切换环境如果重新配置太麻烦。
SpringBoot引入了Profile功能可以帮助我们方便切换环境配置,具体信息参照 Spring官方文档 。
为了方便多环境适配,SpringBoot简化了Profile功能。
3.1 切换环境配置功能
可以参照 测试环境配置文件命名规则
的方式来命名:application-<env>.yaml
(env为环境名称,名称可以任意定义)。
3.1.1 使用配置文件属性指定环境配置
使用方式是在默认环境配置文件中指定spring.profiles.active
属性,值为自定义的环境名称。
编写一个控制器来演示Profile功能:
@RestController
public class UserController {
@Value("${user.username:默认环境}") // 使用SpEL表达式取配置文件中的值进行注入,默认值为“默认环境”
private String name;
@GetMapping("/name")
public String getUserName() {
return "Hello, " + name;
}
}
上述代码中的name
属性将取SpringBoot配置文件中的user.username
属性的值。
编写测试环境的配置文件(application-test.yaml
):
user:
username: 测试环境
server:
port: 8081
编写生产环境的配置文件(application-prod.yaml
):
user:
username: 生产环境
server:
port: 8082
编写默认环境的配置文件(application.yaml
):
# spring.profiles.active属性用于指定当前激活的环境配置
spring:
profile:
active:
不指定spring.profiles.active
属性时SpringBoot会使用默认环境配置,发送/name
请求测试,测试结果:
指定spring.profiles.active
属性为test
即测试环境时会使用测试环境配置,发送/name
请求测试,测试结果:
指定spring.profiles.active
属性为prod
即生产环境时会使用生产环境配置,发送/name
请求测试,测试结果: