Recently whilst taking an interest in some Spring features from Spring in Action, I decided to take a closer look at Spring AOP in particular.
More precisely, I wanted to find out the benefits of this mechanism in the context of Mule. To begin with, I decided to apply some ‘advice’ around a Mule component in a Flow.
AOP in general is intended for cross cutting concerns where you would like to apply some side concerns to a class without tight-coupling this code with existing code. A few common uses of this are application logging, auditing and transaction handling.
Another AOP solution is AspectJ, which seems to be the recommended tool for applications which require heavy use of AOP concepts and features. Spring AOP leverages some of AspectJ’s features. However, one advantage of using Spring AOP over AspectJ is that with the former no explicit aspects compiler is required. For more information on this comparison please go here or refer to Spring in Action.
In the following example we will apply some “advice” code at four separate “point cuts” on a component class:
Before advice – Run before the method execution
After returning advice – Run after the method returns a result
After throwing advice – Run after the method throws an exception
Around advice – Run around the method execution, combine all three advices above.
The following is a Mule configuration where a Spring file is imported. This is followed by a simple flow with an HTTP inbound endpoint and a component which points to a bean defined in “aop.xml”. The component must point to a bean rather than a class directly. This is so that Spring is able to apply the defined point-cuts on the class.
The following Spring beans file defines the component class above, the advice class and which methods from the advice class to use per point-cut.
The advice class is a simple class which includes code that will be applied to a point-cut:
For more information about the “around” advice please see the following example.
Although this example does very little whilst intercepting messages in a component, one may see how it is possible to apply logic to a Mule application (before, after etc) a message is processed by a component. The same behaviour may be applied anywhere in Mule rather than just on a component, for example at the connector level when receiving a message.
Running the above app by invoking the HTTP endpoint will give the following in logs: