常規配置都得采用@value進行屬性配置,屬性值比較少的狀況下還能夠接受,可是屬性值多的狀況下就比較麻煩了。spring
springboot 爲咱們提供了一種比較簡單的注入方法!安全
基於properties文件類型安全配置,代碼以下springboot
直接在application.properties文件中配置bash
w.name = wang
w.sex = boy
複製代碼
Studentapp
@Component
@ConfigurationProperties(prefix = "w")
public class Student {
String name;
String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' + ", sex='" + sex + '\'' + '}'; } } 複製代碼
controlleride
@Autowired
private Student student;
//類型安全的配置
@RequestMapping("student")
@ResponseBody
public Student getUser1() {
return student;
}
複製代碼
結果測試
{"name":"wl","sex":"boy"}ui
** 能夠自定義properties文件 **this
a.propertiesspa
w.name = wang
w.sex = boy
複製代碼
此次不在application文件裏面配置,咱們在外面新建的配置文件。
因此此次咱們必須在Student上指定一下文件的路徑
@PropertySource(value = "classpath:a.properties")
咱們在來測試:
{"name":"wl","sex":"boy"}