This example project shows how to implement a custom CDI context with all the extras (including activation and deactivation). This branch uses CDI 2.0 and Weld 3.x.
Suppose we have a simple functional interface:
public interface Command {
void execute();
}
Our mission is to provide a custom context so that it's possible to create bean instances whose lifecycle is bound to the command execution.
In other words, a @CommandScoped
bean instance should be destroyed after the execution completes.
As a bonus we would like to be able to inject CommandExecution
metadata (and see for example the time an execution started at).
First of all, we need to provide a scope annotation:
@NormalScope
public @interface CommandScoped {
}
Note that the scope is normal. This implies few facts and requirements:
- whenever you inject a
@CommandScoped
bean you get a client proxy, this allows e.g. to inject a@CommandScoped
bean into@ApplicationScoped
bean - there may be no more than one mapped bean instance per
@CommandScoped
bean per thread
See also the spec - 6.3. Normal scopes and pseudo-scopes.
The other important class is CommandContextImpl
.
Few things to notice:
ThreadLocal
is used to store the map of bean instances- there must be a way to activate/deactivate the context - see also
activate()
anddeactivate()
methods InjectableCommandContext
is an injectable version of context which allow to detect the original "activator", so that it's possible to skip deactivation duringdeactivate()
ContextualInstance
wrapper allows to create and destroy a bean instance properly
The custom context can be activated/deactivated either by CommandDecorator
, CommandExecutor
or manually - a @Dependent
bean with bean type CommandContext
and qualifier @Default
is automatically registered.
See also the tests and compare the different ways of activating the context.
All the tests use Weld SE programmatic bootstrap API. This allows us to:
- run the tests as regular unit tests - no Java EE container is needed
- disable automatic discovery and gain the full control of scanning