开发者

How to load a variable in the ServletContext when application initializes using stripes and guice?

I have read answer regarding loading variable when app starts in stripes

In that KDeveloper has adviced to use Guice to load singleton object instead of the other techniques he has specified. I have loaded variable using Guice. But I am not able to load the variable when application starts. I don't want the 开发者_JS百科variable to be loaded whenever a new connection occurs. I want a stripes + guice specific answer.

Is anybody out there can help me out ? Thanking you guys in advance.


If you want Guice singletons to start at application start, you need to bind them with asEagerSingleton() otherwise they will start on first usage. Example code::

package com.myapp.myguice;

import com.google.inject.AbstractModule;

public class ApplicationModule extends AbstractModule {

  @Override
  protected void configure() {
    bind(MySingleton.class).asEagerSingleton();
  }
}

The singleton could look like this:

package com.myapp.myguice;

import com.google.inject.Inject;

public class MySingleton {
  private String myValue;

  @Inject
  MySingleton() {
    myValue = UnkownAPI.getMyValue();
  }

  public String getMyValue() {
    return myValue;
  }
}

Make sure you have both Guice and Stripes-Guice jar files added to your project/classpath and that you have configured your web.xml like this:

<context-param>
  <param-name>Guice.Modules</param-name>
  <param-value>com.myapp.myguice.ApplicationModule</param-value>
</context-param>
<listener>
  <listener-class>
    com.silvermindsoftware.stripes.integration.guice.GuiceContextListener
  </listener-class>
</listener>

If you need to inject the singleton into an actionBean, then please read: Guice Managed Action Beans. It would look like this:

public class MyAction implements ActionBean {

  private final MySingleton mySingleton;

  @Inject
  MyAction(MySingleton mySingleton) {
    this.mySingleton = mySingleton;
  }

  ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜