同以前的 properties 用法,springboot 采用 yml 配置文件。
'#'
表示注释单引号
表示字符串内容会被转义 、双引号
表示字符串内容不转义k: v
k: [v1,v2,v3]
或者
k:
- v1
- v2
- v3
k: {k1:v1,k2:v2,k3:v3}
或者
k:
k1: v1
k2: v2
k3: v3
application.yml:
person:
userName: zhangsan
boss: false
birth: 2019/12/12 20:12:33
age: 18
pet:
name: tomcat
weight: 23.4
interests: [篮球,游泳]
animal:
- jerry
- mario
salarys: [3999,4999.98,5999.99]
pets: [{name: pet1,weight: 47},{name: pet2,weight: 50}]
score:
english:
first: 30
second: 40
third: 50
math: [131,140,148]
chinese: {first: 128,second: 136}
allPets:
sick:
- {name: tom}
- {name: jerry,weight: 47}
health: [{name: mario,weight: 47}]
配置类Person:
@Data
@Component
@ConfigurationProperties("person")
public class Person {
private String userName;
private Boolean boss;
private Date birth;
private Integer age;
private Pet pet;
private String[] interests;
private List<String> animal;
private Set<Double> salarys;
private List<Pet> pets;
private Map<String, Object> score;
private Map<String, List<Pet>> allPets;
@Override
public String toString() {
return "Person{" +
"userName='" + userName + '\'' +
",\n boss=" + boss +
",\n birth=" + birth +
",\n age=" + age +
",\n pet=" + pet +
",\n interests=" + Arrays.toString(interests) +
",\n animal=" + animal +
",\n salarys=" + salarys +
",\n pets=" + pets +
",\n score=" + score +
",\n allPets=" + allPets +
'}';
}
}
依赖类Pet:
@Data
public class Pet {
private String name;
private Double weight;
}
启动类:
@SpringBootApplication
public class App
{
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
Person person = (Person) context.getBean("person");
System.out.println(person);
}
}
运行结果:
Person{userName='zhangsan',
boss=false,
birth=Thu Dec 12 20:12:33 CST 2019,
age=18,
pet=Pet(name=tomcat, weight=23.4),
interests=[篮球, 游泳],
animal=[jerry, mario],
salarys=[3999.0, 4999.98, 5999.99],
pets=[Pet(name=pet1, weight=47.0), Pet(name=pet2, weight=50.0)],
score={english={first=30, second=40, third=50}, math={0=131, 1=140, 2=148}, chinese={first=128, second=136}},
allPets={sick=[Pet(name=tom, weight=null), Pet(name=jerry, weight=47.0)], health=[Pet(name=mario, weight=47.0)]}}