spring實(shí)現(xiàn)靜態(tài)注入(類或者屬性)操作示例
spring實(shí)現(xiàn)靜態(tài)注入類或者屬性
場(chǎng)景是:工具類一般都是靜態(tài)方法,靜態(tài)方法只能訪問(wèn)靜態(tài)屬性。所以,我們需要靜態(tài)注入類或者屬性。
常規(guī)操作:
注入類或者方法:
@Autowired private TestService testService; @Resource private TestService testService; @Value("${key}") private String key;
這樣,我們就把容器里的類和Enviroment里的值注進(jìn)去了。
靜態(tài)注入操作:
我們使用相同的方式進(jìn)行注入
@Autowired private static TestService testService; @Resource private static TestService testService; @Value("${key}") private static String key;
我們?cè)陟o態(tài)方法使用的時(shí)候,會(huì)出現(xiàn)null;
發(fā)現(xiàn)注入不進(jìn)去。
靜態(tài)注入失敗解決兩種方式
- (1)@PostConstruct方式實(shí)現(xiàn)
@Component?? public?class?TestUtil?{ @Autowired private?static?TestService?testService; private?static?TestUtil?testUtils; @PostConstruct?????? public?void?init()?{?????????? testUtils?=this;?????????? testUtils.testService?=this.testService;?????? }?? }
@PostConstruct 注解的方法在加載類的構(gòu)造函數(shù)之后執(zhí)行,也就是在加載了構(gòu)造函數(shù)之后,執(zhí)行init方法;
(@PreDestroy 注解定義容器銷毀之前的所做的操作)這種方式和在xml中配置 init-method和 destory-method方法差不多,定義spring 容器在初始化bean 和容器銷毀之前的所做的操作;
- (2)set方法注入實(shí)現(xiàn)
@Component?? public?class?TestUtil?{ private?static?TestService?testService; private?static?String?key; @Value("{key}") public?void?setTestService(String?key)?{?????????? TestUtil.key?= key;?????? }?? @Autowired public?void?setTestService(TestService?testService)?{?????????? TestUtil.testService?=this.testService;?????? }?? }
ok,完事,使用set方法注入,這種使用比較多
以上就是spring實(shí)現(xiàn)靜態(tài)注入(類或者屬性)操作示例的詳細(xì)內(nèi)容,更多關(guān)于spring靜態(tài)注入類屬性的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
dom4j創(chuàng)建和解析xml文檔的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇dom4j創(chuàng)建和解析xml文檔的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06java實(shí)現(xiàn)簡(jiǎn)易外賣訂餐系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡(jiǎn)易外賣訂餐系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10MyBatis綁定錯(cuò)誤提示BindingException:Invalid bound statement (not f
這篇文章主要介紹了MyBatis綁定錯(cuò)誤提示BindingException:Invalid bound statement (not found)的解決辦法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的的朋友參考下吧2017-01-01springcloud干貨之服務(wù)注冊(cè)與發(fā)現(xiàn)(Eureka)
這篇文章主要介紹了springcloud干貨之服務(wù)注冊(cè)與發(fā)現(xiàn)(Eureka) ,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01Spring Cloud Feign內(nèi)部實(shí)現(xiàn)代碼細(xì)節(jié)
Feign 的英文表意為“假裝,偽裝,變形”, 是一個(gè)http請(qǐng)求調(diào)用的輕量級(jí)框架,可以以Java接口注解的方式調(diào)用Http請(qǐng)求,而不用像Java中通過(guò)封裝HTTP請(qǐng)求報(bào)文的方式直接調(diào)用。接下來(lái)通過(guò)本文給大家分享Spring Cloud Feign內(nèi)部實(shí)現(xiàn)代碼細(xì)節(jié),感興趣的朋友一起看看吧2021-05-05