Spring给类中静态变量赋值

http://caohongxing7604.blog.163.com/blog/static/32016974200861761122206/

Spring中静态类使用,转载自:http://www.aimiclub.com/blogdetail.cmd?blogid=10000178

Spring的设计原则是尽可能的用实例,且是尽可能多的用单态实例,从它Bean的配置文件中就可以知道。不过有时注入并不是最好的处理方法,特别是对于遗留类的处理,可能用静态类是更好的处理方法,因为静态类不需要注入,就不需要太多的改变原来的代码。Spring的注入有一个问题就是普通类没有办法获得Bean文件中的bean实例。这就是如果是在Web的Servlet环境中可以通过WebApplicationContextUtils,如果是普通类就不好处理了。这需要一点设计的技巧。下面是一个静态类使用Bean文件中实例的例子

public class UserinfoUtil

{

    private IUserInfo userInfo;

    private static UserinfoUtil info;

    public void setUserInfo(IUserInfo userInfo)

    {

        this.userInfo = userInfo;

    }

    public void init()

    {

        info = this;

        info.userInfo = this.userInfo;

    }

    public static int addUserLoginCnt(String phonenumber)

    {      

        return info.userInfo.addUserLoginCnt(phonenumber);

    }

}


相应的Bean文件的配置

  
<bean id="userinfoUtil" class="com.huawei.aimi.webportal.service.UserinfoUtil" init-method="init">

         <property name="userInfo" ref="userInfo"/>

  </bean>


这样就可以用静态灶来访问Spring的单例配置了

有几点需要注意的地方

1.一定要用初始化方法,如果没有init方法直接在构造器中,如果用new ()实例就会出现问题

2.this一定也只能在init方法中使用,不能在构造器中使用

3.不要去实现Spring 的相关接口,而应当使用初始化方法

猜你喜欢

转载自panyongzheng.iteye.com/blog/1678065