[Development] Spring - Spring inject static variables

  Today encounter a problem, one of my utility class provides several static methods, static methods need another instance of a class to provide treatment, and therefore write code like this:

 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 }

  Here is the way getBean used to obtain examples XXX, but others say this approach is not good, the way you want to inject.

  But how static XXX inject it?

  Internet search a lot to say, is simple:

 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();
    }      
}

  In the normal configuration xml inject it.

<bean value="test" class="x.x.x.Util">
    <property value="xxx" ref="xxx"/>
</bean>

  Note here that automatically generate getter and setter methods, will be with qualifier static, the need to remove before they can.

Reproduced in: https: //my.oschina.net/u/204616/blog/545181

Guess you like

Origin blog.csdn.net/weixin_33896069/article/details/91989576