Sun GlassFish Enterprise Server v3 Add-On Component Development Guide

HK2 Runtime

Once Services are defined, the HK2 runtime can be used to instantiate or retrieve instances of services. Each service instance has a scope, specified as singleton, per thread, per application, or a custom scope.

Scopes of Services

You can specify the scope of a service by adding an org.jvnet.hk2.annotations.Scoped annotation to the class-level of your @Service implementation class. Scopes are also services, so they can be custom defined and added to the HK2 runtime before being used by other services. Each scope is responsible for storing the service instances to which it is tied; therefore, the HK2 runtime does not rely on predefined scopes (although it comes with a few predefined ones).

@Contract
public abstract class Scope {
	public abstract ScopeInstance current();
}

The following code fragment shows how to set the scope for a service to the predefined Singleton scope:

@Service
public Singleton implements Scope {
    ...
}

@Scope(Singleton.class)
@Service
public class SingletonService implements RandomContract {
    ...
}

You can define a new Scope implementation and use that scope on your @Service implementations. You will see that the HK2 runtime uses the Scope instance to store and retrieve service instances tied to that scope.

Instantiation of Components in HK2

Do not call the new method to instantiate components. Instead, retrieve components by using the ComponentManager instance. The simplest way to use the ComponentManager instance is through a getComponent(ClassT contract) call:

public <T> T getComponent(Class<T> clazz) throws ComponentException;

More APIs are available at ComponentManager.

HK2 Lifecycle Interfaces

Components can attach behaviors to their construction and destruction events by implementing the org.jvnet.hk2.component.PostConstruct interface, the org.jvnet.hk2.component.PreDestroy interface, or both. These are interfaces rather than annotations for performance reasons.

The PostConstruct interface defines a single method, postConstruct, which is called after a component has been initialized and all its dependencies have been injected.

The PreDestroy interface defines a single method, preDestroy, which is called just before a component is removed from the system.


Example 2–1 Example Implementation of PostContruct and PreDestroy

@Service(name="com.example.container.MyContainer")
public class MyContainer implements Container, PostConstruct, PreDestroy {
	@Inject
	Logger logger;
	...
	public void postConstruct() {
		logger.info("Starting up.");
	}

	public void preDestroy() {
		logger.info("Shutting down.");
	}
}