SpringBoot有多种拉取配置的方式,本文主要介绍两种方式拉取配置文件:
一,拉取核心配置文件application.yml
1.直接使用@Vlaue注入
application.yml:
server:
port: 9001
testKey : value1
Controller
@RestController
@RequestMapping("/get")
public class getValueTest {
@Value("${testKey}")
public String value;
@RequestMapping("properties")
public String getValue(){
return value;
}
}
我们在开发项目时常常会有几种环境,比如beta,dev,test环境等等,不同的环境某些参数就会不一样,配置文件不一样,这种时候我们使用@Value注解更为方便。只需在yml或者启动类里指定以哪个环境运行。
spring:
profiles:
active: dev
或者:
2.使用Environment方式注入
Evnironment在声明时加上@Autowired注解即可完成依赖注入,原理是在Evnironment初始化时,springBoot会把当前环境的配置文件注入到Evnironment里,然后使用env.getProperty(“键名”)即可读取出对应的值。
application.yml:
server:
port: 9001
testKey : value1
Controller
@RestController
@RequestMapping("/get")
public class getValueTest {
@Autowired
private Environment evnironment;
@RequestMapping("/properties")
public String getValue(){
return evnironment.getProperty("testKey");
}
}
二,拉取自定义配置文件
平时我们在开发中,我们也会自定义一些配置,像这些配置,我们可以声明配置类和其对应,如下:
application.yml
server:
port: 9001
testKey : value12
user.name : jiao
user.address : SHANGHAI
controller:
@RestController
@RequestMapping("/get")
public class getValueTest {
@Autowired
private Environment evnironment;
@Autowired
private CustomConfig customConfig;
@RequestMapping("/myProperties")
public String getUser(){
return customConfig.getName()+","+customConfig.getAddress();
}
}
配置类:
@Component
@ConfigurationProperties(prefix = "user")
public class CustomConfig {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}