Interceptors and Decorators tutorial

In this tutorial we will show two advanced features of CDI programming: Interceptors and Decorators. We will introduce them by using the Kitchesink example which will be upgraded to use these features.

An Interceptor is a class that is used to interpose in method invocations or lifecycle events that occur in an associated target class. The interceptor performs a separation of concern activity by doing tasks, such as logging or auditing, that are not related with the business logic of the application and that are repeated often within an application.

CDI Interceptors are pretty much the same as EJB interceptors, however since they are applied using a qualifier, you will at first define your interceptor qualifier, for example, here is a Log qualifier (which can be triggered by adding the @Log annotation on your Beans):


public @interface Log { }

Notice the @InterceptorBinding annotation which differentiates this specifies that this qualifier will be used as an Interceptor.

And now will code the Interceptor definition, which bears the qualifier annotation (@Log) at the top of it:



import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

import org.jboss.logging.Logger;

public class LoggingInterceptor implements Serializable {

    private static final Logger logger =
     public Object logMethodEntry(InvocationContext ctx) throws Exception {
 "Before entering method:" + ctx.getMethod().getName());
           return ctx.proceed();

As you can see, this Interceptor barely traces method calling writing this information to the application logger. The ctx.proceed() just as for EJBs interceptors, will continue in the list of other Interceptors or finally land on the Bean method.

Now we can apply this annotation either at class level (and will intercept all method calls) or at method level, so it will intercept just that method call. Let’s apply it to the MemberController bean so that it will trace the main application lifecycle:

public class MemberController {

    private FacesContext facesContext;

    private MemberRegistrationInt memberRegistration;

    private Member newMember;

    public void initNewMember() {
        newMember = new Member();

    public void register() throws Exception {
        try {
            FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "Registered!", "Registration successful");
            facesContext.addMessage(null, m);
        } catch (Exception e) {
            String errorMessage = getRootErrorMessage(e);
            FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Registration unsuccessful");
            facesContext.addMessage(null, m);

    private String getRootErrorMessage(Exception e) {
        // Default to general error message that registration failed.
        String errorMessage = "Registration failed. See server log for more information";
        if (e == null) {
            // This shouldn't happen, but return the default messages
            return errorMessage;

        // Start with the exception and recurse to find the root cause
        Throwable t = e;
        while (t != null) {
            // Get the message from the Throwable class instance
            errorMessage = t.getLocalizedMessage();
            t = t.getCause();
        // This is the root cause message
        return errorMessage;


In order to let your Interceptor kick-in, you need to declare it into your beans.xml file:


What about the order of interceptors ? in case you have more than one interceptor that will be used in your Bean, the order will be determined by your beans.xml, so for example, supposing that you have the following interceptors (bound respectively to LoggingInterceptor1 and LoggingInterceptor2):

public void register() throws Exception {

. . . . .

Here the LoggingInterceptor2 will be invoked at first since we have configured it as first in beans.xml


Additionally, if you have got several Interceptors in your chain, you can allow your interceptor inherit from another one, so with a single annotation you can describe a complex chain of interceptors.

This can be done by adding the @Inherited annotation and stating the qualifiers we are inheriting inside the qualifier. Here the @ComplexLog qualifier inherits from our @Log qualifier;

@Target({ TYPE, METHOD })
public @interface ComplexLog {

thus, once you have coded your ComplexLog Interceptor class, you can trigger both interceptors by simply adding to your Bean:

public void register() throws Exception {

CDI Decorators tutorial

A decorator is a Java class that is annotated javax.decorator.Decorator and that has a corresponding decorators element in the beans.xml file.

The decorator bean class implements an interface and defines, through a delegate injection point (annotated with @Delegate), which field, method or constructor needs to be decorated.

Let’s take as example the MemberRegistration Bean which stores on the DB every user which registers.

Here’s the core part of it:

public class MemberRegistration implements MemberRegistrationInt {
. . .

    public void register(Member member) throws Exception {"Registering " + member.getName());

Now we want to “decorate” the register method so that we can provide an alternate execution and (if needed) invoke as well the main method. Here we will trace on the application server data directory, each user that registered:

public class RegistrationDecorator implements MemberRegistrationInt{
    @Inject @Delegate MemberRegistrationInt registration;

    public void register(Member member) throws Exception {

         BufferedWriter bw = null;

         try {
                 // Writes into the AS data dir a log of all users registered.
           bw = new BufferedWriter(new FileWriter(System.getProperty("") +"/kitchensink.dat", true));
           bw.write("Registering User "+member.toString());
          } catch (IOException ioe) {
          } finally {
              if (bw != null) try {
         } catch (IOException ioe2) {  ioe2.printStacktrace();  }
              // Now calls the Member registration method



Notice the usage of the @Decorator class which declares it as a Decorator.  The annotation:
    @Inject @Delegate MemberRegistrationInt registration;
Specifies the injection point, which will be on the MemberRegistrationInt interface. In order to activate decorators you need to declare them in your beans.xml file:


Decorators vs Interceptors vs Alternatives

Decorators bear some similarities with Interceptors and with  Alternatives as well.

Decorators and Interceptors are similar because they can be both used to “enrich” or “decorate” one method call with additional tasks. However Interceptors are used for general tasks, which are not related with your class in particular (e.g. auditing). On the other hand, Decorators, do bear with them the Bean attributes/operations so they can actually specialize or override a specific business functionality

Decorators and Alternatives are similar as well because they can be used to provide different implementations for your use cases. However Alternative beans can be used to provide a whole different bean implementation, while decorators can be used to further specialize a single method/attribute and they allow as well interacting with the method/attribute we are going to specialize.


Download the code

The source code for this example can be downloaded from my fork of Jboss AS 7 quickstart, available at: