Monthly Archives: October 2015

CDI Context: it is possible without scope annotations in your API!


If you never implemented a CDI context/scope it is a simple as implementing this interface:

public interface Context {
   Class<? extends Annotation> getScope();
   <T> T get(Contextual<T> component, CreationalContext<T> creationalContext);
   <T> T get(Contextual<T> component);
   boolean isActive();
}

Note: in CDI 1.1 there is AlterableContext too which just adds a destroy(Contextual) method which is not important for this post so I will ignore it but I would recommand you to use it instead of Context if you can rely on CDI 1.1.

The Context implementation is quite simple:

  • isActive() returns true if the context is usable by the CDI container
  • getScope() returns the associated annotation (often @XXXScoped)
  • get(Contextual) returns the instance of the Contextual (~= Bean) for “current” context
  • get(Contextual, CreationalContext) creates or returns current instance

Creating a scope “annotation” is as easy as creating a runtime annotation:

// @NormalScope(passivating=false)
@Target({ METHOD, TYPE, FIELD })
@Retention(RUNTIME)
public @interface WrappingMethodScoped {
}

Note: the @NormalScope is optional since it can be done by an extension – this is what we’ll do.

Now we know what is a CDI scope let see how to activate it programmatically.

Continue reading