【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的實例,可是別人說這個方法很差,想要注入的方式。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的限定符,須要去掉,才能夠。blog

相關文章
相關標籤/搜索