Powerful combination: JMX + Annotation + AOP

What is AOP?

AOP is a way to modularize cross-cutting concerns. Ok, what does “modularize” really mean? Modularization is the encapsulation of a unit of functionality. It is exactly what “Class” is doing in OO world. How about “cross-cutting concerns”? Basically it means any functionalities that span multiple modules/ classes. They include Transaction Management, Security, Caching, Performance Monitoring and etc. To understand how AOP works, we first look at the common terms in this area:

  1. Join point – An identifiable point in the execution of a program like method invocation, exception thrown.
  2. Pointcut – Program construct that selects join points and collects context at those points. AspectJ has a rich pointcut expression language!
  3. Advice – Code to be executed at a join point that has been selected by a pointcut.

To me, I found it easier to understand these terms if I consider join point as event generated point in code, pointcut as a way to define what events to be captured and advice as event handler.

AOP is indeed a powerful way to factor out system or infrasturcture-related code from the business oriented code. Typically, we use it to take care of transaction, security and profiling aspects. But it doesn’t stop you putting creativity in this domain. With a bit more creativity, you can also do the following::

  1. Exception translation – checked to runtime
  2. Catch ConcurrencyFailureExceptions and transparently retry if an idempotent operation fails with, for example, a deadlock loser exception.

How I use Spring AOP in my project?

I have been told to report the elapsed time for all calls to the database. If I don’t know how to use AOP, I may end up putting code to measure time for every JDBC calls. It ends up tangling performance monitoring code with my main line business logic and the same logic will be scattered everywhere in my data access code. Bad!! That is why we need to know how to factor out the performance monitoring code into an aspect like below:

Here we use AspectJ annotation approach to implement the aspect. “Around” is to intercept start and end of any repository method. Here is what states in Spring 2.5 reference:

Spring 2.0 introduces a simpler and more powerful way of writing custom aspects using either a schema-based approach or the @AspectJ annotation style. Both of these styles offer fully typed advice and use of the AspectJ pointcut language, while still using Spring AOP for weaving.

If you use AspectJ annotation, you need to put <aop:aspectj-autoproxy/> in your application-context.xml. The limitation of Spring proxy-based AOP is that it is limited to method invocation interception. To get around that, you can use AspectJ syntax in your pointcut expression. You don’t need to build the application with ajc (the AspectJ compiler) even you are using AspectJ syntax. Spring AOP can also understand @AspectJ aspects. I strong suggest you use Annotation driven AOP because it is cleaner and simplier. Working with AOP, I have faced 2 questions.

  1. How to select the methods that I want to intercept without hardcoding the method or package name in my pointcut expression. So, my aspect or pointcut doesn’t contain application specific information – Look into annotation and AOP section.
  2. How to turn on and off AOP without restarting the web application? I would use JMX. Look into “What is JMX” section. 

Annotation and AOP

Annotation provides a better way other than code signature for selecting join point that leads to creating loosely coupled aspect. In fact, you can see annotation as another signature of a method in other dimension. And a method can have multiple annotations and each concern just bother its own annotation. It is called multidimensional signature space. For example,

@Authentication(“bankOperation”)
@Transactional(REQUIRED)
public void credit(){…}

Pointcut uses annotation to capture join points. For example:

execution(@Transactional * *.*(..)) Execution of a method annotated as Transactional
execution((@Trasactional *) *.*(..)) Execution of a method that returns object annotated as Transactional
execution(* (@Transactional *).*(..)) Execution of a method defined for type annotated as Transactional

Selection can use Annotation types and Annotation values.  What is more, annotation values can be used in Advice implementation.

Here is a great video from Parleys that talked about “Leveraging Annotation with AOP”. I have included some key points Ramnivas made here:

  • Write you pointcut in a smart way to avoid annotation mess. Try to use naming and package convention to help you. For example, if you want to write app log for all public facing service method, you can use “public” with package name containing “service” wildcard to help you.
  • If you really need to use annotation like @Transaction that designer has no way to define the pointcut beforehand, use annotation to describe what the join point is but not how to handle it. So, your transaction aspect only need to worry annotation @Transaction and decouple from the application.
  • You can piggyback annotation. For example, you can make all entities auditable via declare @type: @Entity *: @Auditable; 

How does Spring AOP work internally?

The magic behind AOP is the concept of Proxy/ Decorator/ Interceptor/ Filter pattern. To me, all those patterns are conceptually the same. They all try to present itself as target object (thru implementing the same interface), intercept method call and execute injected logics. And you can have more than one interceptors invoked in series. In Spring AOP, there is one thing we need to pay attention:

However, once the call has finally reached the target object, …any method calls that it may make on itself, such as this.bar() or this.foo(), are going to be invoked against the this reference, and not the proxy. This has important implications. It means that self-invocation is not going to result in the advice associated with a method invocation getting a chance to execute. To handle this, either you refactor your code such that the self-invocation does not happen (best approach) or you make self invocation call thru proxy like ((Pojo) AopContext.currentProxy()).bar() (invasive approach b/c it totally couples your code to Spring AOP, and it makes the class itself aware of the fact that it is being used in an AOP context, which flies in the face of AOP. Avoid using it).

However, it must be noted that AspectJ does not have this self-invocation issue because it is not a proxy-based AOP framework.

What is JMX?

In short, it is a way to enable management and monitoring of Java applications over a generic API. JMX has a simple architecture that contains instrumentation level, agent level and distribution service level. In instrumentation layer, we register MBean to the MBeanServer. In simple term, In simple term, MBean is a  JavaBean with defined management interface that exposes attributes and operations to the world. MBeanServer acts as a broker to decouple communication among application MBeans and/or remote clients.

Combine AOP and JMX

AOP is statically defined and intercept at the runtime. It is hard to take this out or add another aspect in after you start your machine. However, with JMX, you can enable and disable it via skipping the aspect code. :cool: On the other hand, you can also use JMX to configure and report SLA metrics like configure thresholds and send notifications of violations. That sounds very interesting to me. There are other interesting usages mentioned in the Parley’s video as well:

  1. Service blocking – throw an exception if particular service you don’t want to user to use it for a period of time esp during maintenance time.
  2. Caching management – I am currently using interceptor pattern and IoC to intercept dao method calls for cache lookup. 

Reference

  1. JavaOne 07 – JMX, AOP and Spring (Nice Presentation)
  2. Parley’s AOP and JMX (Video)
  3. Simplifying Enterprise Applications with Spring 2.0 and AspectJ
  4. Workflow Orchestration Using AOP
  5. Performance Monitoring with AOP and JMX

 

Leave a comment

0 Comments.

Leave a Reply

You must be logged in to post a comment.