Spring不克不及注入Static變量的緣由及Spring注入靜態變量。本站提示廣大學習愛好者:(Spring不克不及注入Static變量的緣由及Spring注入靜態變量)文章只能為提供參考,不一定能成為您想要的結果。以下是Spring不克不及注入Static變量的緣由及Spring注入靜態變量正文
上面給年夜家引見spring不克不及注入static變量的緣由,詳細概況以下所示:
Spring 依附注入 是依附 set辦法
set辦法是 是通俗的對象辦法
static變量是類的屬性
@Autowired private static JdbcTemplate jdbcTemplate;
純真看這個注入進程是沒有報錯的,然則在接上去的jdbcTemplate.query()會報空指針毛病.
ps:Spring注入靜態變量
明天碰著一個成績,我的一個對象類供給了幾種靜態辦法,靜態辦法須要別的一個類的實例供給處置,是以就寫出了如許的代碼:
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若何注入呢?
上彀查了許多的說法,其實很簡略:
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的限制符,須要去失落,才可以。