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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

@EnableConfigurationProperties注解

發布時間:2023/12/20 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 @EnableConfigurationProperties注解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

1.概述

2.測試

2.1 使用?@EnableConfigurationProperties?進行注冊

2.2 使用 @Component 注冊

3.項目中的使用場景


1.概述

@EnableConfigurationProperties注解的作用是:使 使用 @ConfigurationProperties 注解的類生效。

如果一個配置類只配置@ConfigurationProperties注解,而沒有使用@Component或者實現了@Component的其他注解,那么在IOC容器中是獲取不到properties 配置文件轉化的bean。說白了 @EnableConfigurationProperties 相當于把使用 @ConfigurationProperties 的類進行了一次注入。

簡單點說@EnableConfigurationProperties的功能類似于@Component。

2.測試


2.1 使用?@EnableConfigurationProperties?進行注冊

@ConfigurationProperties(prefix = "service.properties") public class HelloServiceProperties {private static final String SERVICE_NAME = "test-service";private String msg = SERVICE_NAME;set/get }@Configuration @EnableConfigurationProperties(HelloServiceProperties.class) @ConditionalOnClass(HelloService.class) @ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true) public class HelloServiceAutoConfiguration {}@RestController public class ConfigurationPropertiesController {@Autowiredprivate HelloServiceProperties helloServiceProperties;@RequestMapping("/getObjectProperties")public Object getObjectProperties () {System.out.println(helloServiceProperties.getMsg());return myConfigTest.getProperties();} }

配置文件application.properties

service.properties.name=my-test-name service.properties.ip=192.168.1.1 service.user=kayle service.port=8080

一切正常,但是 HelloServiceAutoConfiguration 頭部不使用 @EnableConfigurationProperties,測訪問報錯。

2.2 使用 @Component 注冊

不使用 @EnableConfigurationProperties 進行注冊,使用 @Component 注冊

@ConfigurationProperties(prefix = "service.properties") @Component public class HelloServiceProperties {private static final String SERVICE_NAME = "test-service";private String msg = SERVICE_NAME;public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}}

Controller 不變,一切正常,如果注釋掉 @Component 測啟動報錯。
由此證明,兩種方式都是將被 @ConfigurationProperties 修飾的類,加載到 Spring Env 中。


?

3.項目中的使用場景

如下,在配置類NacosConfigAutoConfiguration的頭上加注解@EnableConfigurationProperties(NacosConfigProperties.class),

而在NacosConfigProperties配置類本身并沒有實現了@Component相關的注解,也就是說運行項目時,不會直接把NacosConfigProperties配置類注入到Spring 容器中,而是在執行NacosConfigAutoConfiguration這個配置類時才會去把NacosConfigProperties類注入到spring

?

如下,NacosConfigProperties類本身并沒有@Component相關注解:

參考鏈接:關與 @EnableConfigurationProperties 注解 - 簡書

?

總結

以上是生活随笔為你收集整理的@EnableConfigurationProperties注解的全部內容,希望文章能夠幫你解決所遇到的問題。

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