Jersey-Guice doesn't process bound resources if injector is a child?

孤人 提交于 2019-12-06 00:14:17

I figured it out after some fun with the debugger.

The resources are discovered by iterating over the bindings of the injector, checking for those that are resources or providers. The injector used is injected into the GuiceContainer via a constructor like this: public GuiceContainer(@Inject injector). With no explicit binding for GuiceContainer.class specified in the child injector, the parent (i.e., root) injector is used to create the instance (just-in-time binding, I guess) and consequently the parent (not the child) injector is injected into to the GuiceContainer instance.

The fix is simple:

Explicitly bind GuiceContainer.class in the child injector. The following code works

 public class MyConfig extends GuiceServletContextListener {
     final Injector parentInjector;

     public MyConfig(Injector injector) {
         this.parentInjector = injector;
     }

     @Override
     protected Injector getInjector() {
         return parentInjector.getChildInjector(new ServletModule() {
             @Override
             protected void configureServlets() {
                 /* Explicitly bind GuiceContainer so that
                  * the child, not root, injector is injected 
                  * into its constructor. */
                 bind(GuiceContainer.class);
                 bind(MyResource.class);
                 serve("*").with(GuiceContainer.class);
             }
         });
     }
 }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!