users@hk2.java.net

Populating ServiceLocator in Jersey 2

From: Miles Pomeroy <pomeroymiles_at_gmail.com>
Date: Tue, 21 Jan 2014 19:52:40 -0700

I'd like to have automatic service population in my Jersey 2 app. The
Jira issue <https://java.net/jira/browse/HK2-165> mentions that this
is possible but not documented. The author appears to understand how
to do this and intimates that an end-user can do the same by digging
"through the source-code". Can someone help me figure this out?

I've added the `hk2-inhabitant-generator` maven plugin to my project.
Then I tried copying some code from the
`ServiceLocatorUtilities.createAndPopulateServiceLocator` method into
my Jersey Application class.

public class App extends ResourceConfig {

    @Inject
    public App(ServiceLocator serviceLocator) {
        DynamicConfigurationService dcs =
            serviceLocator.getService(DynamicConfigurationService.class);
        Populator populator = dcs.getPopulator();

        try {
            populator.populate();
        } catch (IOException e) {
            throw new MultiException(e);
        }

        packages("com.milespomeroy.jersey2jdbi2hk2.rest");
        registerInstances(new MyBinder());
    }

}

But this didn't work. I'm still getting an
`org.glassfish.hk2.api.UnsatisfiedDependencyException` when injecting
a @Service class into my Jersey resource.

@Service
public class MagicService {
    public int getMagicNumber() {
        return 42;
    }
}

@Path("/service")
public class ServiceResource {
    @Inject
    private MagicService magicService;

    @GET
    @Produces("text/plain")
    public String getMagicNumber() {
        return "The magic number is " + this.magicService.getMagicNumber();
    }
}

Miles.