Enterprise Java

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 :
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Quester
Quester
8 years ago

Which implementation does get injected as delegate to SocialFeedDecorator. Both SocialFeedProcessor implemetations are qualified with same qualifier annotation.

Back to top button