Sun GlassFish Enterprise Server v3 Add-On Component Development Guide

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.