在spring boot中,我們用 @ConfigurationProperties 用來将properties/yaml檔案中的值可以注入到javabean中,取代了我們以前的applicationContext.xml檔案注入的方式。
具體方式是:
@Component //下面的注解依賴于這個注解,必須要将對象放在spring容器中才能使用
@ConfigurationProperties(prefix = "person") //書寫這個是從yml檔案中擷取名為person的資料
public class Person {
private String name;
private Integer age;
private Boolean boss;
private Map<String, Object> maps;
private List<Object> list;
private Dog dog;
public get/set();
public toString();
但是同樣,我們也可以用@Value的方式進行值的注入
public class Person {
@Value("lisi")
private String name;
@Value("${person.age}") //從配置檔案中擷取值
private Integer age;
private Boolean boss;
private Map<String, Object> maps;
private List<Object> list;
private Dog dog;
public get/set();
public toString();
那他們的差別在哪裡呢?
簡單一句話,當隻需要用一次資料時,就可以通過@Values("${…}")來擷取資料。
當需要專門将JavaBean中的資料進行綁定時,就用@ConfigurationProperties