Java EE6 Decorators, decorating classes at injection time
Join the DZone community and get the full member experience.
Join For FreeA 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.
1 | @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>
From http://styledideas.be/blog/2011/06/22/java-ee6-decorators-decorating-classes-at-injecting-time/
Opinions expressed by DZone contributors are their own.
Comments