這篇文章將為大家詳細(xì)講解有關(guān)spring將配置信息注入靜態(tài)變量的案例,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
傳統(tǒng)的錯(cuò)誤作法
application.properties
spring.redis.host=test
@Component public class RedisServiceImpl implements RedisService { ... @Value("${spring.redis.host}") static public String host; @Value("${spring.redis.port}") static public Integer port; ... static public JedisPool getJedisPool() { if (RedisServiceImpl.host == null) { logger.info("host 未注入"); } }
控制臺(tái)打印為: "host 未注入
正確的方法
@Component public class RedisServiceImpl implements RedisService { ... static public String host; static public Integer port; @Value("${spring.redis.host}") public void setHost(String host) { RedisServiceImpl.host = host; } @Value("${spring.redis.port}") public void setPort(Integer port) { RedisServiceImpl.port = port; } ... static public JedisPool getJedisPool() { if (RedisServiceImpl.host == null) { logger.info("host 未注入"); } else { logger.info("host 值為" + RedisServiceImpl.host); } }
控制臺(tái)正確的打印了注入的值。
原因猜想
spring
進(jìn)行組件掃描,遇到@Component
時(shí),初始化對(duì)象 RedisServiceImpl
, 初始化過程中,掃描到@Value
注解,將值注入給方法。
接著,方法將值傳給了RedisServiceImpl
類,故RedisServiceImpl
有值 -- 正解。
如果將@Value(),
直接加到靜態(tài)私有變量上,則在初始化對(duì)象時(shí),由于靜態(tài)私有變量屬于類,所以spring未對(duì)類進(jìn)行操作 -- 錯(cuò)誤。
關(guān)于“spring將配置信息注入靜態(tài)變量的案例”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
文章名稱:spring將配置信息注入靜態(tài)變量的案例-創(chuàng)新互聯(lián)
網(wǎng)站鏈接:http://chinadenli.net/article16/cdjddg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、自適應(yīng)網(wǎng)站、網(wǎng)站營銷、域名注冊、動(dòng)態(tài)網(wǎng)站、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容