Spring Boot读取yml
Spring Boot也可以通过@Value和@ConfigurationProperties注解来读取application.yml文件的属性值。
1 @Value
1.1 基本类型
1)配置
nickname: eric
age: 20
2)SpringBoot读取配置
/**
* @Value注解 - 读取application.yml
* 一点教程网 - www.yiidian.com
*/
@Controller
public class ConfigController {
//1.1 读取基本类型
@Value("${nickname}")
private String nickname;
@Value("${age}")
private Integer age;
1.2 JavaBean类型
1)配置
user:
nickname: jack
age: 18
2)SpringBoot读取配置
/**
* @Value注解 - 读取application.yml属性
* 一点教程网 - www.yiidian.com
*/
@Controller
public class Config2Controller {
//1.2 读取JavaBean类型
@Value("${user.nickname}")
private String nickname;
@Value("${user.age}")
private Integer age;
1.3 数组/List集合
1)配置
user:
list: eric,jack,rose
2)SpringBoot读取配置
/**
* @Value注解 - 读取application.yml属性
* 一点教程网 - www.yiidian.com
*/
@Controller
public class Config3Controller {
//1.3 读取数组/List集合类型
@Value("#{'${user.list}'.split(',')}")
private List<String> list;
1.3 Map集合
1)配置
user:
map: "{nickname: 'eric',age: 20}"
2)SpringBoot读取配置
/**
* @Value注解 - 读取application.yml属性
* 一点教程网 - www.yiidian.com
*/
@Controller
public class Config4Controller {
//1.4 读取Map集合类型
@Value("#{${user.map}}")
private Map<String,Object> map;
2 @ConfigurationProperties
2.1 基本类型
1)配置
nickname: eric
age: 20
2)SpringBoot读取配置
/**
* @ConfigurationProperties注解 - 读取application.yml属性
* 一点教程网 - www.yiidian.com
*/
@Controller
@ConfigurationProperties(prefix = "")
public class Config5Controller {
//1.1 读取基本类型
private String nickname;
private Integer age;
public void setNickname(String nickname) {
this.nickname = nickname;
}
public void setAge(Integer age) {
this.age = age;
}
注意以下几点:
- prefix:代表属性的前缀,如果user.nickname前缀就是user
- 属性名称必须和properties文件的属性名保持一致
- 属性必须提供setter方法来注入文件的属性值
2.2 JavaBean类型
1)配置
user:
nickname: jack
age: 18
2)SpringBoot读取配置
/**
* @ConfigurationProperties注解 - 读取application.yml属性
* 一点教程网 - www.yiidian.com
*/
@Controller
@ConfigurationProperties(prefix = "user")
public class Config6Controller {
//1.2 读取JavaBean类型
private String nickname;
private Integer age;
public void setNickname(String nickname) {
this.nickname = nickname;
}
public void setAge(Integer age) {
this.age = age;
}
2.3 数组/List集合
1)配置
user:
list2:
- eric
- jack
- rose
2)SpringBoot读取配置
/**
* @ConfigurationProperties注解 - 读取application.properties属性
* 一点教程网 - www.yiidian.com
*/
@Controller
@ConfigurationProperties(prefix = "user")
public class Config7Controller {
//1.3 读取数组/List集合类型
private List<String> list2;
public void setList2(List<String> list2) {
this.list2 = list2;
}
2.4 Map集合
1)配置
user:
map2: {nickname: eric,age: 20}
2)SpringBoot读取配置
/**
* @ConfigurationProperties注解 - 读取application.yml属性
* 一点教程网 - www.yiidian.com
*/
@Controller
@ConfigurationProperties(prefix = "user")
public class Config8Controller {
//1.4 读取Map集合类型
private Map<String,Object> map2;
public void setMap2(Map<String, Object> map2) {
this.map2 = map2;
}
热门文章
优秀文章