[轉]spring 注入靜態變量

原文: http://www.cnblogs.com/xing901022/p/4168124.htmlhtml

今天碰到一個問題,個人一個工具類提供了幾種靜態方法,靜態方法須要另一個類的實例提供處理,所以就寫出了這樣的代碼:工具

複製代碼
 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的實例,可是別人說這個方法很差,想要注入的方式。this

  可是靜態的XXX如何注入呢?spa

  上網查了不少的說法,其實很簡單:code

複製代碼
 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 value="test" class="x.x.x.Util">
    <property value="xxx" ref="xxx"/>
</bean>

  這裏要注意,自動生成的getter和setter方法,會帶有static的限定符,須要去掉,才能夠。htm

相關文章
相關標籤/搜索