users@hk2.java.net

Re: Populating ServiceLocator in Jersey 2

From: John Wells <john.wells_at_oracle.com>
Date: Thu, 23 Jan 2014 07:55:46 -0500

I think you need to modify your code just a little. I assume that your
META-INF/hk2-locator/default files are present in your application
archive. If that is so then you might want to try giving the
classloader to the populate call like this:

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

This uses this:

https://hk2.java.net/2.2.0/apidocs/org/glassfish/hk2/utilities/ClasspathDescriptorFileFinder.html

This assumes that a getResources call on that classloader will find the
META-INF/hk2-locator/default files that are in your archive.

Hope this helps,

John Wells
john.wells_at_oracle.comNOSPAM

On 1/22/2014 9:21 AM, cowwoc wrote:
> 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.
>