Search code examples
javajerseyjax-rshk2

bindFactory does not inject fields


I have this code to provide a custom injectable object:

    config.register(new AbstractBinder() {
        @Override
        protected void configure() {
            delegatorFactory = ...; //custom factory to delegate to
            bindFactory(new Factory<Object>() {
                @Inject
                private Provider<ContainerRequestContext> req;

                @Override
                public void dispose(Object arg0) {
                }

                @Override
                public Object provide() {
                    // req is needed but is null
                }
            }).to(delegatorFactory.getType()).in(RequestScoped.class);
        }
    });

Unfortunately, as the comment in provide() reveals, the req field is not injected when it is executed (I need the ContainerRequestContext at that location). What am I missing to make it work like this, i.e. make the factory's fields injected?


Solution

  • Bind it with a class. Most of time, when you start instantiating stuff yourself, you lose the benefit of injection. So just use a class

    bindFactory(YourFactoryClass.class)
    

    UPDATE

    To get the injector to manually inject the factory, you can use a Feature

    public class YourFeature implements Feature {
        @Override
        public void configure(FeatureContext context) {
            final ServiceLocator locator = ServiceLocatorProvider.getLocator(context);
    
            locator.inject(anyObject);
      
            context.register(new YourAbstractBinder());
        }
    }
    
    config.register(new YourFeature());