users@hk2.java.net

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

From: Mason Taube <mason.taube_at_oracle.com>
Date: Thu, 5 Dec 2013 16:25:45 -0500

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> wrote:

> When you getService(contract), and are using the inhabitant generator, how does it know which @Contract links to what @Service?