Aspect-Oriented Programming in Apache Camel

Apache Camel has a very powerful bean injection framework which allows developers to focus only on solving business problems. However there are situations when you need to do a little bit more. Read below to see how easy it is to setup aspects (AspectJ) in Apache Camel.


Use case


In Qualitas I have an installation route which consists of 10 mandatory and 2 optional processors. Some processors like property resolvers or validators don't modify contents of message's body so I have to always copy body from the in message to out message. Also, all my processors require some headers to function properly. Finally, I would like to get a status updated after each of my processors either finishes processing successfully or fails.


Setting up AspectJ


This is just a plain Spring configuration frankly. All you have to do is:

<aop:aspectj-autoproxy />

Apache Camel processor aspect


To define aspect in AspectJ I used AspectJ-specific @Aspect and @Around annotations:

@Aspect
@Component
@Order(Ordered.LOWEST)
public class HeadersAndBodyCopierAspect {
    @Around("execution(* com.googlecode.qualitas.internal.installation..*.process(org.apache.camel.Exchange)) && args(exchange) && target(org.apache.camel.Processor)")
    public Object copyHeadersAndBody(ProceedingJoinPoint pjp, Exchange exchange) throws Throwable {
        Object retValue = pjp.proceed();
        Message in = exchange.getIn();
        Message out = exchange.getOut();
        // always copy headers
        out.setHeaders(in.getHeaders());
        // if output body is empty copy it from input
        if (out.getBody() == null) {
            out.setBody(in.getBody());
        }
        return retValue;
    }
}

I also used @Order Spring-specific annotation to control the order of execution of my aspects and @Component for automatic context scanning.


Now, the join point is defined as execution(* com.googlecode.qualitas.internal.installation..*.process(org.apache.camel.Exchange)) && args(exchange) && target(org.apache.camel.Processor) which basically means:


  1. apply this aspect to all process methods which are defined in all classes in com.googlecode.qualitas.internal.installation or subpackages and which take Exchange object as an argument
  2. there can be many custom methods whose names may be process and whose argument may be Exchange, so I added one more constraint, this class has to be an instance of Processor
  3. args(exchange) allows me to add Exchange object as an argument to my aspect

More complex aspects and source code


Of course in Spring you can inject other beans directly into your aspects. I used it in my ProcessStatusUpdaterAspect aspect which you can find in Qualitas repo on GoogleCode or GitHub.


If you are interested in trying out the whole Qualitas system take a look at the following two links: BuildingTheProject and RunningTheProject.


cheers,

Łukasz

 

 

 

 

Top