日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

@EnableConfigurationProperties 注解和@ConfigurationProperties注解实现配置绑定

發布時間:2023/12/10 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 @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=100

mycar就是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注解实现配置绑定的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。