I’m really starting to wrap my head around AOP and really like the idea of abstracting out cross-cutting concerns and removing it from my core business code. So far I’ve been reading up on AOP Alliance (which I see is the workhorse for Guice and Spring AOP) and AspectJ.
Unfortunately, good, working Java AOP code examples are hard to come by when we are talking about anything more advanced than simple method interception. I keep reading over and over again how major Java EE concepts such as Persistence, Transaction Handling and Messaging can be implemented with AOP, but for the life of me I can’t find any examples of this!
Ultimately speaking, at the end of the day, AOP does just boil down to method interception (unless I’m missing something major here). So if that’s the case, and given the general form of a method interceptor:
// Using AOP Alliance for this example
public class MyInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation inv) {
// Run this code before executing inv.
preInvocation();
Object result = inv.proceed();
// Run this code after executing inv.
postInvocation();
}
// ...
}
Given that as a starting point, can someone please provide concrete code examples for how each of these Java EE concepts can be delegated to AOP via method interception:
- Persistence/ORM
- Transaction Handling
- Messaging
I guess I’m just having difficulty connecting all the dots and seeing the “forest” through the “trees”. Thanks in advance!
No idea for persistence and messaging, but for transactions, I can explain. I’ll take the example of Spring.
You can configure your Spring beans (typically service layer beans) so that every method invoked on those beans will be intercepted by a transactional interceptor. This interceptor typically does the following thing:
With no transactional aspect the transactional methods would have to do something like this:
It’s cumbersome, error-prone, and doesn’t even handle transaction propagation, new transactions, etc.
With AOP, the body of the method becomes: