天天看點

Spring開發-- Spring注入靜态變量

今天碰到一個問題,我的一個工具類提供了幾種靜态方法,靜态方法需要另外一個類的執行個體提供處理,是以就寫出了這樣的代碼:

1 Class Util{
 2   private static XXX xxx;
 3   xxx = BeanUtil.getBean("xxx");
 4   public static void method1(){
 5      xxx.func1();  
 6   }
 7   public static void method2(){
 8      xxx.func2();
 9   }      
10 }      

  這裡是使用的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的限定符,需要去掉,才可以。

繼續閱讀