Search code examples
javajerseyhk2

HK2 / Jersey does not Inject into non Resource class


I am using jersey to inject POJOs on various locations. Here is my config:

 register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(Bar.class).to(Bar.class).in(Singleton.class);
            bindFactory(FooFactory.class).to(Foo.class).in(Singleton.class);
            ...
        }
    });

FooFactory:

public class FooFactory implements Factory<Foo> {
    @Override
    public Foo provide() {
        return Foo.newInstance();
    }
}

Injecting into a resource works:

@Path("/myresource")
public class MyResource{
     @Inject
     protected Bar instance;
}

But

public class Foo {
     @Inject
     protected Bar instance;
}

does not. Foo.instance is null. Why? And how to make it work?


Solution

  • Your factory is creating Foo, so the DI framework won't attempt any more injections. You need to either let the DI framework create instances of Foo or handle the injection yourself in FooFactory.

    Your FooFactory could, for example, have a Bar field, which it uses to initialise Foo with...

    public class FooFactory implements Factory<Foo> {
        private final Bar theBar;
    
        @Inject
        public FooFactory(Bar bar) {
            theBar = bar;
        }
    
        @Override
        public Foo provide() {
            return Foo.newInstance(bar);
        }
    }