Search code examples
javadependency-injectionjerseyhk2

Do I need to use a factory in order to inject a simple object in Jersey?


As of right now in order to inject an object of type Foo into Bar I do the following.

Class to be injected into:

class Bar {
    @Inject
    Foo field;

    public Foo getField() { return field; }
}

Code implementing Factory:

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

    @Override
    public void dispose(Foo f) {
    }
}

Code in Main Configuration:

final ResourceConfig rc = new ResourceConfig()
                .packages("com.example")
                .register(
                        new AbstractBinder() {
                            @Override
                            protected void configure() {
                                bindFactory(new FooFactory()).to(Foo.class).in(Singleton.class);
                            }
                        })

My question is... In Jersey 2.0 which uses hk2 for dependency injection is there anyway to inject an object without creating a factory class?


Solution

  • It is possible to use an AbstractBinder for injection binding without a Factory or an InjectionResolver.

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

    In this case the classes Foo and Bar have empty constructors.

    public class Bar {
        @Inject
        Foo field;
        public Foo getField() { return field; }
    }
    
    public class Foo {}
    

    Now you can inject Bar into a resource or other hk2 beans.