Spring不能注入Static變量的原因及Spring注入靜態(tài)變量
下面給大家介紹spring不能注入static變量的原因,具體詳情如下所示:
Spring 依賴注入 是依賴 set方法
set方法是 是普通的對象方法
static變量是類的屬性
@Autowired private static JdbcTemplate jdbcTemplate;
單純看這個注入過程是沒有報錯的,但是在接下來的jdbcTemplate.query()會報空指針錯誤.
ps:Spring注入靜態(tài)變量
今天碰到一個問題,我的一個工具類提供了幾種靜態(tài)方法,靜態(tài)方法需要另外一個類的實例提供處理,因此就寫出了這樣的代碼:
Class Util{ private static XXX xxx; xxx = BeanUtil.getBean("xxx"); public static void method(){ xxx.func(); } public static void method(){ xxx.func(); } }
這里是使用的getBean的方式,獲得XXX的實例,但是別人說這個方法不好,想要注入的方式。
但是靜態(tài)的XXX如何注入呢?
上網查了很多的說法,其實很簡單:
Class Util{ private static XXX xxx; public void setXxx(XXX xxx){ this.xxx = xxx; } public void getXxx(){ return xxx; } public static void method1(){ xxx.func1(); } public static void method2(){ xxx.func2(); } }
在xml中正常配置注入就可以了。
<bean value="test" class="x.x.x.Util"> <property value="xxx" ref="xxx"/> </bean>
這里要注意,自動生成的getter和setter方法,會帶有static的限定符,需要去掉,才可以。
相關文章
SpringMVC4.3?HandlerExceptionResolver異常處理源碼解析
這篇文章主要為大家介紹了SpringMVC4.3?HandlerExceptionResolver異常處理源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪<BR>2023-09-09