@ConfigurationProperties和@Value

青青於我心發表於2021-01-01

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

不支援

支援

 

 

 

 

 

 

 

 

相關文章