application.properties配置
person.name=admin
person.address=shanghai
person.email=123
person.map.k1=v1
person.map.k2=v2
先看一下@ConfigurationProperties的使用
/**
* 支持Validated校验
*/
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
private String name;
private String address;
@Email
private String email;
private Map<String, Object> map;
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", email='" + email + '\'' +
", map=" + map +
'}';
}
}
输出:
Person{name='admin', address='shanghai', email='123@qq.com', map={k1=v1, k2=v2}}
再看一下@Value的使用
/**
* value注解不支持复杂类型,如map,list
*/
@Component
public class PersonValue {
@Value("${person.name}")
private String name;
@Value("${person.address}")
private String address;
//value注解支持SpEl表达式
@Value("#{20}")
private int age;
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "PersonValue{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
}
输出
PersonValue{name='admin', address='shanghai', age=20}
总结
@ConfigurationProperties | @Value | |
是否支持校验 | 支持 | 不支持 |
是否支持复杂类型 | 支持 | 不支持 |
SpEl | 不支持 | 支持 |