1 SpringBoot常见的配置文件形式
常⻅的配置⽂件格式
xml、properties、json、yaml
xx.yml形式的配置文件YAML(Yet Another Markup Language)
注意:key后⾯的冒号,后⾯⼀定要跟⼀个空格,树状结构
server:
port: 8080 //设置启动端⼝号为8080
house:
family:
name: Doe
parents:
- John
- Jane
children:
- Paul
- Mark
- Simone
address:
number: 34
street: Main Street
city: Nowheretown
zipcode: 12345
xx.properties形式的配置文件
Key=Value格式
语法简单,不容易出错
server.port=8082
#session失效时间,30m表示30分钟
server.servlet.session.timeout=30m
# Maximum number of connections that the server accepts and processes at
any given time.
server.tomcat.max-connections=10000
# Maximum size of the HTTP post content.
server.tomcat.max-http-post-size=2MB
server.tomcat.max-http-form-post-size=2MB
# Maximum amount of worker threads
server.tomcat.max-threads=200
2 配置文件读取方式
2.1 在controller中定义属性,通过@Value注解取值
- 在resources目录下创建配置文件:testconfig.properties
test.username = jackyan
test.password = 666666
- 编写TestController
Controller上⾯配置 @PropertySource({"classpath:testconfig.properties"})
增加属性 @Value("${test.username}") private String username;
@RestController
@RequestMapping("/app/v1/test")
@PropertySource({"classpath:testconfig.properties"}) # 添加此注解说明配置文件名称
public class TestController {
@Value("${test.username}") # 定义配置属性
private String username;
@Value("${test.password}") # 定义配置属性
private String password;
@RequestMapping("get_config")
public Object getConfig() {
Map<String, String> map = new HashMap<>();
map.put("username", username);
map.put("password", password);
return map;
}
}
- 测试取值
2.2 通过实体类取值
- 创建与controller同级的包config,在config下创建配置类TestConfig
@Configuration # 说明此文件是配置文件类
@PropertySource(value = "classpath:testconfig.properties") # 设置配置文件路径
public class TestConfig {
@Value("${test.username}") # 获取配置属性
private String username;
@Value("${test.password}") # 获取配置属性
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- 在Controller中测试获取配置
@RestController
@RequestMapping("/app/v1/test")
public class TestController {
@Autowired
private TestConfig testConfig; # 注入配置类
@RequestMapping("get_config")
public Object getConfig() {
Map<String, String> map = new HashMap<>();
map.put("username", testConfig.getUsername());
map.put("password", testConfig.getPassword());
return map;
}
}
- 测试结果
正常获取配置