Guice + Jersey integration injects null objects

2019-06-09 21:00发布

Following the excellent step-by-step given in Up and running on AppEngine with Maven, Jersey and Guice - Part 3, I have been able to get everything working except injecting objects into a Jersey POJO.

The only difference I have from that configuration is that I also have Objectify integrated, but that is working.

The TestClass instance (a singleton) injected into HelloWorldServlet works, but the TestClass and SecondTest (RequestScoped) objects injected into the HeyResource POJO are always null.

I suspect the the interaction between HK2 and Guice is to blame here, but this is my first project with Guice and Jersey and HK2, so I am all at sea.

My configuration is:

  • Platform: Win 7
  • GAE SDK 1.9.26
  • Jave 1.7.0_79
  • Jersey: 2.5.1
  • Guice: 4.0
  • Objectify: 5.1.7
  • HK2 Guice-bridge: 2.2.0
  • Maven 3.3.3

1条回答
何必那么认真
2楼-- · 2019-06-09 21:10

With Jersey 2 you don't need to use the Guice web wrapper like was needed with Jersey 1. You already have the guice-bridge, you just need to configure it with HK2 within the Jersey configuration. See The Guice/HK2 Bridge.

You basically need to get a handle on the HK2's ServiceLocator to bind the two frameworks. Jersey allows you to inject the locator in many locations of the application. The place where you would need it most is in the configuration class (i.e. the ResourceConfig). Here is an example of how you can configure it.

public class JerseyConfig extends ResourceConfig {

    @Inject
    public JerseyConfig(ServiceLocator locator) {
        packages("your.packages.to.scan");

        GuiceBridge.getGuiceBridge().initializeGuiceBridge(locator);
        // add your Guice modules.
        Injector injector = Guice.createInjector(new GuiceModule());
        GuiceIntoHK2Bridge guiceBridge = locator.getService(GuiceIntoHK2Bridge.class);
        guiceBridge.bridgeGuiceInjector(injector);
    }
}

If you are using web.xml to configure the app, you can add this class to your configuration with an init-param

<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.stackoverflow.jersey.JerseyConfig</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
查看更多
登录 后发表回答