Java Reference
In-Depth Information
that you can employ to resolve these types of ambiguities. You will encounter several of these during
the course of this topic. If curiosity has gotten the better of you, skip to Chapter 5.
Context is the distinguishing feature between EJBs and CDI‐managed beans. CDI beans exist
within a dei ned context; EJBs do not. CDI beans are created within the context of a scope; they
exist for the life of the scope and are destroyed when the scope i nishes. There are four scopes
that are annotated as follows: @ApplicationScope , @ConversationScope , @SessionScope , and
@RequestScope . The CDI container controls the life of a bean based on the bean's dei ned scope.
For example, a bean annotated with @SessionScope exists for as long as the HTTP session is alive;
at the end the scope, the bean is destroyed and marked for garbage collection. This behavior is
in contrast to that of EJBs, which are not bound to a scope. This means that you must explicitly
remove the bean by calling a method annotated by the @Remove annotation.
INTERCEPTORS
Most applications have concerns that don't comfortably i t into the core concern of the application
logic but cannot be cleanly separated from the application's design or implementation. These
concerns are cross‐cutting and affect different parts of the application. They are often responsible
for duplicate code and interdependencies that make the system less extensible. The implementation
of these noncore concerns as interceptors allows them to be decoupled from the core concern. You
do this by logically separating their implementation and intercepting method calls to the core and
invoking the appropriate method.
You implement interceptors using the annotation @Interceptors followed by the class name of the
crossing‐cutting concern. In Listing 2‐4, the setValue method is intercepted upon its invocation by
the LoggerInterceptor.class .
LISTING 2‐4: Core method intercepted by logger interceptor
@Interceptors(LoggerInterceptor.class)
public void setValues(Integer value, String name) {
this.value = value;
this.name = name;
}
The logger interceptor can access the intercepted method's parameters and perform the cross‐cutting
logic before returning to fully execute the intercepted method.
In Listing 2-5, the logger interceptor accesses the parameters of the setValues method and logs
them to the system logger.
LISTING 2‐5: The logger interceptor
@AroundInvoke
public logger(InvocationContext ic) throws Exception {
Object[] params = ic.getParameters();
logger.warning("Parameters passed: " + params);
}
 
Search WWH ::




Custom Search