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 :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


three − = 2



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close