Over a million developers have joined DZone.
Platinum Partner

Java EE6 Decorators, decorating classes at injection time

· Java Zone

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.

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.

public class TicketServiceImpl implements TicketService {
    private EntityManager entityManager;
    public Ticket orderTicket(String name) {
        Ticket ticket = new Ticket(name);
        return ticket;

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

public class TicketServiceDecorator implements TicketService {
    private TicketService ticketService;
    private CateringService cateringService;
    public Ticket orderTicket(String name) {
        Ticket ticket = ticketService.orderTicket(name);
        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"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

From http://styledideas.be/blog/2011/06/22/java-ee6-decorators-decorating-classes-at-injecting-time/

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}