在springboot中读取yml的配置并封装成配置类需要如下几个注解
@ConfigurationProperties(prefix = “person”)表示读取前缀为person的配置,其中prefix可以是用.分割的多个层级
@ConfigurationProperties prefix默认为"",建议指定前缀,避免属性名称冲突,且指定前缀yml与java config对应更清晰
@Configuration表示这是一个配置类用于在springboot启动时扫描并加载
为了不用在每个config上都加一个@Configuration注解,可以在启动类中添加@ConfigurationPropertiesScan(basePackages = {“com.test.svc.config”})
com.test.svc.config包下存放全部java config类
person:
id: 1
name: xiaohong
sex: female
age: 15
java config
@Configuration
@ConfigurationProperties(prefix = "person")
@Data
public class MyConfig {
private Integer id;
private String name;
private String sex;
private Integer age;
}
yml中定义的列表,在java中可以用集合或数组识别
列表中每个元素都以-开头
yml
person:
list:
- id: 1
name: xiaohong
sex: female
age: 15
- id: 2
name: xiaoming
sex: male
age: 20
java config
@Configuration
@ConfigurationProperties(prefix = "person")
@Data
public class MyConfig {
private List<Person> list; //这个list对应yml中的list
// private Person[] list; yml中配置的列表在java中也可以用数组识别
@Data
public static class Person{
private Integer id;
private String name;
private String sex;
private Integer age;
}
}
字符串中如果有:必须用引号引起来,否则会被识别为键值对
yml
person:
strList:
- "aa:bb"
- bb
- cc
java config
@Configuration
@ConfigurationProperties(prefix = "person")
@Data
public class MyConfig {
private List<String> strList;
//private String[] strList; 也可以识别成数组
}
yml中的数组用>表示,数组的每个元素之间用,分割
字符串中含有:时不需要用引号
不可以表示对象数组
yml
person:
arr: >
aaa:bbb,
bbb,
ccc
java config
@Configuration
@ConfigurationProperties(prefix = "person")
@Data
public class MyConfig {
private String[] arr;
}
yml
person:
map:
1:
id: 1
name: xiaohong
sex: female
age: 15
2:
id: 2
name: xiaoming
sex: male
age: 20
java config
@Configuration
@ConfigurationProperties(prefix = "person")
@Data
public class MyConfig {
private Map<Integer, Person> map;
@Data
public static class Person{
private Integer id;
private String name;
private String sex;
private Integer age;
}
}
yml
person:
map:
1: xiaohong
2: xiaoming
java config
@Configuration
@ConfigurationProperties(prefix = "person")
@Data
public class MyConfig {
private Map<Integer, String> map;
}
yml
list:
- id: 1
name: xiaohong
sex: male
age: 15
- id: 2
- name: xiaoming
sex: female
age: 20
java config
@Configuration
@ConfigurationProperties()
@Data
public class MyConfig {
private List<Person> list;
@Data
public static class Person{
private Integer id;
private String name;
private String sex;
private Integer age;
}
}