Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Comparative Analysis Between Spring AOP and AspectJ

DZone's Guide to

Comparative Analysis Between Spring AOP and AspectJ

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

Aspect-oriented programming(AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. AOP provides aspects that enable modularization of concerns across Objects. Though multiple AOP frameworks are available today, here we are going to differentiate only between two popular frameworks: Spring AOP and AspectJ. This should help you decide the right technology to use in your project based on the key information.

Spring AOP differs from that of most other AOP frameworks. The aim of Spring AOP is not to provide the most complete AOP implementation (although Spring AOP is quite capable); it is rather to provide a close integration between AOP implementation and Spring IoC to help solve common problems in enterprise applications. Given the fact that Spring AOP is easy to implement, this goal of Spring's is one of the strongest points if you are planning to modularize your cross-cutting concerns across Spring beans. But the same goal also acts as a limitation if you are going to modularize your cross-cutting concerns across plain Java Objects instead of Spring beans. On the other hand, AspectJ can be used to modularize cross across plain Java Objects, but requires good knowledge of the subject before implementation.

Before choosing the framework that you would like to implement for your project, there are certain points that would help you decide to choose between Spring AOP and AspectJ (or for that matter any other framework).

Spring AOP’s aim is to provide a close integration between AOP implementation and Spring IoC to help solve common problems in enterprise applications. Determine if you would like to separate cross-cutting concerns (such as transaction management/logging or profiling) across Spring beans and/or across plain objects. If your application is new, you can easily choose to use Spring in your framework. On the other hand, if you are maintaining an existing application (which is not implanted using Spring), AspectJ becomes the natural choice. To elaborate more on this point, say you want to add “logging” as an advice to your application and would like to trace the flow. The advice can then only be applied across the joinpoints of Spring beans when using Spring AOP.

E.g., configuring following pointcut to the appbeans.xml would apply logging advice when service method is going to be called on myServices bean.

<!—Configuration snippet in appbeans.xml -->

  <bean id="myServices" class="com.ashutosh.MyServicesImpl " />

  <aop:config>

    <aop:aspect id="loggingAspect" ref="logging">

       <aop:around method="log" pointcut="execution(public * *(..))"/>

   </aop:aspect>

 </aop:config --> 

// Java file calling service method

ApplicationContext beans =newClassPathXmlApplicationContext("appbeans.xml");

MyServices myServices = (MyServices) beans.getBean("myServices");

myServices.service(); // Logging advice applied here

Check the comment where logging advice would apply and application would print log details of the methods being called. On the other hand if you are going to call a method from within the service() call that exists within the same class, Logging advice would not apply to it, if you are calling a method without taking proxy object.

e.g.

// MyServices service method

public void service() {

  performOperation();// Logging advice not going to apply here

}

If you would like to apply advice on the call of the method on “this” object, you would need to take currentProxy object and would need to call the method on it.

// MyServices service method

public void service() {

  // Logging advice going to apply here

  ((MyServices) AopContext.currentProxy()).performOperation();

}

Similarly if you are going to call method on an object, you would have to change your reference to Spring bean if you would like to apply an advice.

public void service() {

  MyObject obj = new MyObject();

  Obj.performOperation();// Logging advice not going to apply here

}

It would need to be changed to the following code, if you would like to apply this advice.

public void service() {

  MyObject obj = new MyObject();

 Obj.performOperation();// Logging advice not going to apply here

 ApplicationContext beans =newClassPathXmlApplicationContext("appbeans.xml");

 MyObject obj =(MyObject) beans.getBean("myObject");

 obj.performOperation()// Logging advice applied here

}

On the other hand, you may apply advice on any Java object using “AspectJ” without any need to create/configure a bean in any file.  

Another factor you should consider is if you would like to perform weaving at compile time and/or at post-compile/run-time. Spring supports only run-time weaving. If you have multiple teams working on multiple modules (resulting in multiple jar files, i.e. one jar for each module) that are written using Spring. If one of the team members wants to apply logging advice on the whole project (logging is just taken as an example here to add cross cutting concern) across all the Spring beans (i.e., including jar files that has been packaged by another team), it can be done easily by configuring the aspect in their own Spring configuration file. This is possible because of Spring's support of run-time weaving.

<!—Configuration -->

<bean id="myServices" class="com.ashutosh.MyServicesImpl " />

 <aop:config>

  <aop:aspect id="loggingAspect" ref="logging">

      <aop:around method="log" pointcut="execution(public * *(..))"/>

  </aop:aspect>

</aop:config -->

In contrast, if you would like to perform the same through AspectJ, you may need to recompile all your code using ajc (i.e. AspecJ compiler) and would need to re-package your libraries. Otherwise you can opt for either post-compile or load-time weaving with AspectJ.

Since Spring is based on proxy patterns (using CGLIB), it has a limitation that you can not apply cross-cutting concerns across beans that are “final”. Since proxy require to subclass the Java class, it’s not possible once you would use “final” keyword.

e.g. Applying the final keyword on Spring bean MyServicesImpl and configuring a pointcut like “execution(public * *(..))”would result in runtime exception, since Spring would not be able to create a proxy for MyServicesImpl.

// Configuration file

<bean id="myServices" class="com.ashutosh.MyServicesImpl" />

//Java file

public final classMyServicesImpl {

  ---

}

In such scenarios you may like to consider AspectJ, which supports compile time weaving and would not create a proxy for it.

Similarly, if you want to apply cross-cutting concerns across the static and/or final methods, it may not be possible. This is because Spring is based on a proxy pattern. As static and/or final methods cannot be overridden, it would result in a runtime exception, if you configure to apply advice on such methods. In such cases you may consider using AspectJ, which supports compile-time weaving and would not create a proxy for it.

You would certainly like to use an approach that is easy to implement. Since Spring AOP supports annotations, it’s easier to create and configure your aspect using @Aspect annotation. In case of AspectJ, you may need to create your aspect using .aj files (in which case you would write Java that you would like to modularize) and would need to compile your code using ajc (AspectJ Compiler). So if you are certain that the before mentioned limitation may not be hurdle for your project, go for Spring AOP.

One of the indirect limitations of applying AspectJ is that, since it can apply advice works over plain Java, the same advice can get applied over the configured advice (with AspectJ consider this advice as well as a plain Java). This may result in an infinite loop with a pointcut having a wide scope without your knowledge.

E.g., creating aspect with following pointcut with following

public aspectLogging {

  Object around() : execution(public * * (..))

  Sysytem.out.println(thisJoinPoint.getSignature());

  return proceed();

}

In this case, whenever proceed is going to be called, Logging advice would apply again and thus resulting in nested loop.

So if you would like to go for applying a cross-cutting concern using an easier approach on Spring beans, and the beans doesn’t have “final” modifier and similarly method doesn’t have a “static/final” modifier, go for Spring AOP. In contrast, if you would like to apply a cross-cutting concern over mentioned limitations or would like to apply concern over plain Java code, go for AspectJ. You may choose to combine both the worlds as well, as Spring supports the same.

Reference: http://docs.spring.io/spring/docs/3.0.x/reference/aop.html



                                                                           

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
java ,high-perf ,spring ,aop ,logging ,tips and tricks ,aspectj ,aspect ,pointcut ,weaving

Published at DZone with permission of Ashutosh Gupta. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}