users@hk2.java.net

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

From: cowwoc <cowwoc_at_bbs.darktech.org>
Date: Thu, 05 Dec 2013 16:37:54 -0500

Hi Mason,

What prevents you from creating the same binding at runtime? Surely if
hk2-locator can locate this relationship at build-time, you can do the
same at runtime.

Gili

On 05/12/2013 4:25 PM, Mason Taube wrote:
> It figures it out based on the metadata present at runtime. A quick
> example from GlassFish:
>
> WebContainerImpl is annotated with @Service and implements the
> WebContainer interface which is annotated with @Contract.
>
> At build-time the following entry is generated in the appropriate
> META-INF/hk2-locator/default file:
>
> [org.glassfish.web.embed.impl.WebContainerImpl]S
> contract={org.glassfish.embeddable.web.WebContainer}
>
> At runtime, when someone does a
> serviceLocator.getService(WebContainer.class), HK2 scans its indices
> for the WebContainer contract and finds the implementing service.
> There are rules for choosing the right one if more than one is found.
>
> HK2 also adds the implementing class as an advertising contract
> implicitly, so .getService(WebContainerImpl) would also work, but then
> you’re coupled to the implementation class. So you couldn’t inject a
> mock web container for testing for example.
>
>
> On Dec 5, 2013, at 4:00 PM, cowwoc <cowwoc_at_bbs.darktech.org
> <mailto:cowwoc_at_bbs.darktech.org>> wrote:
>
>> When you getService(contract), and are using the inhabitant
>> generator, how does it know which @Contract links to what @Service?
>