users@hk2.java.net

Re: ServiceLocator.getService() failing for _at_Service-annotated classes

From: John Wells <john.wells_at_oracle.com>
Date: Thu, 05 Dec 2013 13:23:57 -0500

I'm also wondering if there isn't some way to make the JIT resolver run
for lookup failures as well, and that way you wouldn't have to do any
wrapping. Sounds like a nice idea for a mini-feature.

On 12/5/2013 1:16 PM, John Wells wrote:
> There isn't. In fact we have a callback that you can use for exactly
> this sort of purpose:
>
> https://hk2.java.net/2.2.0-b25/apidocs/org/glassfish/hk2/api/JustInTimeInjectionResolver.html
>
>
> You can write a simple JIT resolver that does exactly what you are
> asking for.
>
> This will not work for a direct lookup, so you may need something else
> for that case. It'd be fairly easy to write a small wrapper around
> lookup that would try to add the given class if the underlying service
> locator could not find the service.
>
> On 12/5/2013 1:09 PM, cowwoc wrote:
>> John,
>>
>> I just had a thought: why do we need hk2-inhabitant-generator at all?
>> When someone tries to inject a class and a binding is not found,
>> couldn't HK2 automatically add a binding and retry the operation if
>> the class is annotated with @Service? Meaning, what prevents you from
>> adding the binding on-the-fly at runtime?
>>
>> Thanks,
>> Gili
>>
>> On 04/12/2013 6:17 PM, cowwoc wrote:
>>> Thank you. Filed https://java.net/jira/browse/HK2-165
>>>
>>> Gili
>>>
>>> On 04/12/2013 5:58 PM, John Wells wrote:
>>>> To use @Service you must
>>>>
>>>> a) run the hk2-inhabitant-generator as part of your build in order
>>>> to produce the META-INF/hk2-locator/default file. You can look at
>>>> this file to see if it looks reasonable (it should have your
>>>> services in there)
>>>>
>>>> b) Ensure that when you boot hk2 you tell it to read those files in
>>>> (it does not do this automatically). The easiest way to do this is
>>>> with this:
>>>>
>>>> https://hk2.java.net/2.2.0-b25/apidocs/org/glassfish/hk2/utilities/ServiceLocatorUtilities.html#createAndPopulateServiceLocator%28%29
>>>>
>>>>
>>>> I do not currently monitor stackOverflow for hk2, but I will now!
>>>>
>>>> On 12/4/2013 5:37 PM, cowwoc wrote:
>>>>> Hi,
>>>>>
>>>>> I've got something along the lines of:
>>>>>
>>>>> @Service
>>>>> public class TestClass
>>>>> {
>>>>> @Inject
>>>>> public TestClass()
>>>>> {
>>>>> }
>>>>> }
>>>>>
>>>>> public class MyApplication extends ResourceConfig
>>>>> {
>>>>> @Inject
>>>>> public MyApplication(ServiceLocator serviceLocator)
>>>>> {
>>>>> TestClass test = serviceLocator.getService(TestClass.class);
>>>>> }
>>>>> }
>>>>>
>>>>> but serviceLocator.getService(TestClass.class) returns null. What
>>>>> am I missing? Isn't HK2 supposed to auto-bind @Service-annotated
>>>>> classes somehow?
>>>>>
>>>>> PS: Do you monitor the "hk2" tag on Stackoverflow? I think it's a
>>>>> more efficient way of handling recurring questions.
>>>>>
>>>>> Thanks,
>>>>> Gili
>>>>
>>>
>>
>