使用getter、setter方法和xml配置解決spring不能注入static變量。
下面給大家介紹spring不能注入static變量的原因,具體詳情如下所示:
Spring 依賴注入 是依賴 set方法
set方法是 是普通的對象方法
static變量是類的屬性
@Autowired
private static JdbcTemplate jdbcTemplate;
單純看這個注入過程是沒有報錯的,但是在接下來的jdbcTemplate.query()會報空指針錯誤.
找到的一種解決方法:加入geter seter方法
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中正常配置注入就可以了,是的 要在xml裏配置bean,讓人不爽。<bean value="test" class="x.x.x.Util">
<property value="xxx" ref="xxx"/>
</bean>
這裏要注意,自動生成的getter和setter方法,會帶有static的限定符,需要去掉,纔可以。