users@hk2.java.net

Re: Populating ServiceLocator in Jersey 2

From: cowwoc <cowwoc_at_bbs.darktech.org>
Date: Wed, 22 Jan 2014 09:21:24 -0500

Hi Miles,

I forget what my exact code was (I gave up on trying to use Jersey 2)
but at first glance, this code should work.

Gili

On 21/01/2014 9:52 PM, Miles Pomeroy wrote:
> 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.