Sun GlassFish Enterprise Server v3 Prelude Add-On Component Development Guide

Injecting HK2 Components

Services usually rely on other services to perform their tasks. The HK2 runtime identifies the @Contract implementations required by a service by using the org.jvnet.hk2.annotations.Inject annotation. Inject can be placed on fields or setter methods of any service instantiated by the HK2 runtime. The target service is retrieved and injected during the calling service's instantiation by the component manager.

The following example shows how to use @Inject at the field level:

@Inject
ConfigService config;

The following example shows how to use @Inject at the setter level:

@Inject
public void set(ConfigService svc) {...}

Injection can further qualify the intended injected service implementation by using a name and scope from which the service should be available:

@Inject(Scope=Singleton.class, name="deploy")
AdminCommand deployCommand;