环境
SpringBoot 2.2.2.RELEASE
1. SpringBoot 参数配置
1.1 环境准备
- 依赖文件导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
-
参数文件
myconfig: name: configByValue id: 100 desc: myDescByProperty
1.2 使用@Value注解
@RestController
public class MyConfig1 {
@Value("${myconfig.name}")
private String name;
@RequestMapping("/config/value")
public String myConfig() {
return "value annotation:" + name;
}
}
1.3使用@ConfigurationProperties注解
使用@ConfigurationProperties时必须实现get和set方法
@RestController
@ConfigurationProperties(prefix = "myconfig")
@Data
public class MyConfig2 {
private String name;
private int id;
private String desc;
@RequestMapping("/config/property")
public String myConfig() {
return "name:" + name + ",id:" + id + ",desc:" + desc;
}
}
1.4 多环境配置文件
-
环境准备
config/application-test.yml
server: port: 9999
-
准备
config/application-prod.yml
server: port: 8888
-
在application.yml中配置切换标签,根据配置test或者prod,启动的端口不同
spring: profiles: active: prod