下面給大家介紹spring不能注入static變量的原因,具體詳情如下所示:
Spring 依賴注入 是依賴 set方法
set方法是 是普通的對象方法
static變量是類的屬性
1
2
|
@Autowired private static JdbcTemplate jdbcTemplate; |
單純看這個注入過程是沒有報錯的,但是在接下來的jdbcTemplate.query()會報空指針錯誤.
ps:Spring注入靜態變量
今天碰到一個問題,我的一個工具類提供了幾種靜態方法,靜態方法需要另外一個類的實例提供處理,因此就寫出了這樣的代碼:
1
2
3
4
5
6
7
8
9
10
|
Class Util{ private static XXX xxx; xxx = BeanUtil.getBean( "xxx" ); public static void method(){ xxx.func(); } public static void method(){ xxx.func(); } } |
這里是使用的getBean的方式,獲得XXX的實例,但是別人說這個方法不好,想要注入的方式。
但是靜態的XXX如何注入呢?
上網查了很多的說法,其實很簡單:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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中正常配置注入就可以了。
1
2
3
|
<bean value= "test" class = "x.x.x.Util" > <property value= "xxx" ref= "xxx" /> </bean> |
這里要注意,自動生成的getter和setter方法,會帶有static的限定符,需要去掉,才可以。