@EnableConfigurationProperties 注解和@ConfigurationProperties注解实现配置绑定
ConfigurationProperties注解主要用來把properties配置文件轉化為bean來使用的,而@EnableConfigurationProperties注解的作用是@ConfigurationProperties注解生效。如果只配置@ConfigurationProperties注解,在IOC容器中是獲取不到properties配置文件轉化的bean的
如果一個配置類只配置@ConfigurationProperties注解,而沒有使用@Component,那么在IOC容器中是獲取不到properties 配置文件轉化的bean。說白了 @EnableConfigurationProperties 相當于把使用 @ConfigurationProperties 的類進行了一次注入。
測試發現 @ConfigurationProperties 與 @EnableConfigurationProperties 關系特別大。
1:寫法一
1:寫一個Car實體類
類上加上
@Component @ConfigurationProperties(prefix = "mycar")@ConfigurationProperties注解可以把application.properties文件轉化為bean使用@Component注解把該bean注入到IOC容器中。
如果一個類只配置了 @ConfigurationProperties 注解,而沒有使用 @Component 注解將該類加入到 IOC 容器中,那么它就不能完成 xxx.properties 配置文件和 Java Bean 的數據綁定
mycar是在如下application.properties中配置的
?
//只有在容器中的組件,才會擁有springboot的強大的功能 @Component @ConfigurationProperties(prefix = "mycar") public class Car {private String brand;private Integer price;public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}public Integer getPrice() {return price;}public void setPrice(Integer price) {this.price = price;} }?
?
2:在application.properties配置
mycar.brand=BBA mycar.price=100mycar就是Car實體類上
ConfigurationProperties(prefix = "mycar")的
brand和price就是屬性名?
?
3:寫一個Controller類
@RequestMapping("/web/") @RestController public class CarController {@Autowiredprivate Car car;@PostMapping("/test")public Car test1(){return car;} }?
4:用postman進行訪問,看到有返回,能讀取到配置文件中的值
?
?
?
2:寫法二
1:把@Component注解注視掉了,表示不往容器中注冊了
?
?
2:寫一個
SpringConfig配置文件在EnableConfigurationProperties中引入car類
EnableConfigurationProperties只是聲明了屬性綁定
?
3:再次訪問,有返回
?
總結
以上是生活随笔為你收集整理的@EnableConfigurationProperties 注解和@ConfigurationProperties注解实现配置绑定的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 敏捷估计与规划pdf
- 下一篇: hbase权威指南-客户端API高级特性