Spring访问bean

时间:2016-10-14 09:25:49

标签: spring

我的类中的主bean有一个创建起来非常昂贵的对象,因此只能创建一次,然后传递给可能需要它的各种Util。

public class DaemonBean implements InitializingBean
{
   ReallyExpensiveToCreate obj;

   public ReallyExpensiveToCreate getReallyExpensive() { return obj; }

   @Override
   public void afterPropertiesSet()
   {
       //initialize and build ReallyExpensiveToCreate
   }
}

Util类需要该对象,它由一组静态函数组成。

public class Util
{
  public static ReallyExpensiveToCreate objRef = getReallyExpensiveObj();

  private ReallyExpensiveToCreate getReallyExpensiveObj()
  {
     //Get Daemon obj from Spring and call daemonObj.getReallyExpensive();
  }

  public void func1() { //Use objRef in logic }
}

如何从Spring获取守护进程obj。我不确定要调用哪些代码才能引用守护进程obj。我看到了使用ApplicationContext的代码片段,但我不确定如何使用它。

2 个答案:

答案 0 :(得分:1)

您正在寻找服务定位器模式,

Spring中的实现

您可以注册ApplicationContextAware并获取对ApplicationContext和静态服务bean

的引用
public class ApplicationContextUtils implements ApplicationContextAware {
 private static ApplicationContext ctx;

 private static final String USER_SERVICE = "userServiceBean";

  @Override
  public void setApplicationContext(ApplicationContext appContext)
      throws BeansException {
    ctx = appContext;

  }

  public static ApplicationContext getApplicationContext() {
    return ctx;
  }

  public static UserService getUserService(){return ctx.getBean(USER_SERVICE);}

}

答案 1 :(得分:0)

public class Util {

    private static ReallyExpensiveToCreate objRef;

    public void objectFunction() {
        objRef.doSomething();
    }

    public static void staticFunction() {
        objRef.doSomething();
    }

    @Autowired
    public void setReallyExpensiveBeanToCreate(DaemonBean daemonBean) {
        Util.objRef = daemonBean.getReallyExpensive();
    }
}