Java EE6 Decorators: Decorating classes at injection time

A common design pattern in software is the decorator pattern. We take a class and we wrap another class around it. This way, when we call the class, we always pass trough the surrounding class before we reach the inner class.

Java EE 6 lets us create decorators through CDI, as part of their AOP features. If we want to implement cross cutting concerns that are still close enough to the business, we can use this feature of Java EE 6.

Let’s say you have a ticket service that lets you order tickets for a certain event. The TicketService handles the registration etc, but we want to add catering. We don’t see this as part of the ticket ordering logic, so we created a decorator. The decorator will call the TicketService and add catering for the number of tickets.

The interface:

public interface TicketService {
    Ticket orderTicket(String name);
}

The implementation of the interface, creates a ticket and persists it.

@Stateless
public class TicketServiceImpl implements TicketService {
 
    @PersistenceContext
    private EntityManager entityManager;
 
    @TransactionAttribute
    @Override
    public Ticket orderTicket(String name) {
        Ticket ticket = new Ticket(name);
        entityManager.persist(ticket);
        return ticket;
    }
}

When we can’t use a decorator, we can create a new implementation of the same interface.

@Decorator
public class TicketServiceDecorator implements TicketService {
 
    @Inject
    @Delegate
    private TicketService ticketService;
    @Inject
    private CateringService cateringService;
 
    @Override
    public Ticket orderTicket(String name) {
        Ticket ticket = ticketService.orderTicket(name);
        cateringService.orderCatering(ticket);
        return ticket;
    }
}

Notice that we apply 2 CDI specific annotations here. The @Decorator marks the implementation as a decorator. A decorator should always have a delegate, a class we want to decorate, marked with the @Delegate annotation (at the injection point). Also take notice of the fact that we use the interface and not the implementation.

Just like the alternative example, when you inject this interface, the normal implementation will be used.

@Inject private TicketService ticketService;

Instead of using qualifiers, we just have to adjust our beans.xml to mark the TicketServiceDecorator as ‘Decorator’.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <decorators>
        <class>be.styledideas.blog.decorator.TicketServiceDecorator</class>
    </decorators>
</beans>

As a more advanced usage, we can combine a number of decorators and choose the order we want them executed.

If you have a use case for it, you can easily define 2 decorators, by just defining them in the beans.xml file like this.

<decorators>
    <class>be.styledideas.blog.decorator.HighDecorator</class>
    <class>be.styledideas.blog.decorator.LowDecorator</class>
</decorators>

So when we call our decorated class, we get the highdecorator entry, low decorator entry, actual decorated class, low decorator exit, highdecorator exit. So the decorator sequence in the file does matter.

The second feature is more compelling than the first, it exposes the true power of the Decorator feature in java EE6. That is the ability to combine it with CDI annotations. As example I’ll use an Social media feed processor.

So I have created an interface:

public interface SocialFeedProcessor {
    Feed process(String feed);
}

and provided 2 implementations, twitter and google+

public class TwitterFeedProcessor implements SocialFeedProcessor{
 
    @Override
    public Feed process(String feed) {
        System.out.println("processing this twitter feed");
        // processing logics
        return new Feed(feed);
    }
 
}
public class GooglePlusFeedProcessor implements SocialFeedProcessor {
 
    @Override
    public Feed process(String feed) {
        System.out.println("processing this google+ feed");
        // processing logics
        return new Feed(feed);
    }
 
}

I’ll annotate these 2 beans by a custom Qualifier as described here

@javax.inject.Qualifier
@java.lang.annotation.Retention(RUNTIME)
@java.lang.annotation.Target({FIELD, PARAMETER, TYPE})
@java.lang.annotation.Documented
public @interface FeedProcessor {
}

and I annotate my 2 processors with it.

@FeedProcessor
public class TwitterFeedProcessor implements SocialFeedProcessor{
 
    @Override
    public Feed process(String feed) {
        System.out.println("processing this twitter feed");
        // processing logics
        return new Feed(feed);
    }
 
}
@FeedProcessor
public class GooglePlusFeedProcessor implements SocialFeedProcessor {
 
    @Override
    public Feed process(String feed) {
        System.out.println("processing this google+ feed");
        // processing logics
        return new Feed(feed);
    }
 
}

Nothing really special, but now when we write our decorator we use the power of CDI to only decorate the classes with the @FeedProcessor annotation.

@Decorator
public class SocialFeedDecorator implements SocialFeedProcessor {
    @Delegate
    private @FeedProcessor SocialFeedProcessor processor;
 
    @Override
    public Feed process(String feed) {
        System.out.println("our decorator is decorating");
        return processor.process(feed);
    }
}

the only thing that is left is registering our decorator in our beans.xml

<decorators>
    <class>be.styledideas.blog.decorator.SocialFeedDecorator</class>
</decorators>

By using the annotation, we automatically decorate all our implementations of the SocialfeedProcessor with this decorator. When we add an extra implementation of the SocialFeedProcessor without the annotation, the bean will not be decorated.

Reference: Java EE6 Decorators, decorating classes at injection time and Java EE6 Decorators, advanced usage from our JCG partner Jelle Victoor at Styled Ideas Blog.

Related Articles :
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


− 1 = six



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books