Pranav Kapoor
Pranav Kapoor

Reputation: 1281

Spring access to bean

The main bean in my class has an object that is extremely expensive to create and thus is to be created only once and then be passed on to the various Utils that may require it.

public class DaemonBean implements InitializingBean
{
   ReallyExpensiveToCreate obj;

   public ReallyExpensiveToCreate getReallyExpensive() { return obj; }

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

This object is required by the Util class which consists of a set of static functions.

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 }
}

How do I get the Daemon obj from Spring. I'm unsure of what code to call to be able to get reference to the Daemon obj. I saw code snippets where ApplicationContext was used but I am unsure of how that would be used.

Upvotes: 0

Views: 44

Answers (2)

rorschach
rorschach

Reputation: 2947

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

Upvotes: 0

user7018090
user7018090

Reputation:

You are looking for Service-locator pattern,

Implementation in Spring

You can register ApplicationContextAware and get reference to ApplicationContext and statically serve 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);}

}

Upvotes: 1

Related Questions