Guice + Jersey integration injects null objects

蓝咒 提交于 2019-12-23 05:01:26

问题


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:


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>


来源:https://stackoverflow.com/questions/32449706/guice-jersey-integration-injects-null-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!