Spring AOP vs AspectJ

Viewed 85519

I am under the impression that Spring AOP is best used for application specific tasks such as security, logging, transactions, etc. as it uses custom Java5 annotations as a framework. However, AspectJ seems to be more friendly design-patterns wise.

Can anyone highlight the various pros and cons of using Spring AOP vs AspectJ in a Spring application?

8 Answers

This article also has a good explanation regarding the topic.

Spring AOP and AspectJ have different goals.

Spring AOP aims to provide a simple AOP implementation across Spring IoC to solve the most common problems that programmers face.

On the other hand, AspectJ is the original AOP technology which aims to provide complete AOP solution.

It is important to consider whether your aspects will be mission critical and where your code is being deployed. Spring AOP will mean that you are relying on load-time weaving. This can fail to weave and in my experience has meant that logged errors may exist but will not prevent the application from running without aspect code [I would add the caveat that it may be possible to configure it in such a way that this is not the case; but I am not personally aware of it]. Compile-time weaving avoids this.

Additionally, If you use AspectJ in conjunction with the aspectj-maven-plugin then you are able to run unit tests against your aspects in a CI environment and have confidence that built artifacts are tested and correctly woven. While you can certainly write Spring driven unit tests, you still have no guarantee that the deployed code will be that which was tested if LTW fails.

Another consideration is whether you are hosting the application in an environment where you are able to directly monitor the success or failure of a server / application startup or whether your application is being deployed in an environment where it is not under your supervision [e.g. where it is hosted by a client]. Again, this would point the way to compile time weaving.

Five years ago, I was much more in favour of Spring configured AOP for the simple reason that it was easier to work with and less likely to chew up my IDE. However, as computing power and available memory have increased this has become much less of an issue and CTW with the aspectj-maven-plugin has become a better choice in my work environment based on the reasons I have outlined above.

Compared to AOP, AspectJ does not need to enhance the target class at compile time. Instead, it generates a proxy class for the target class at runtime, which either implements the same interface as the target class or is a subclass of the target class.

In summary, an instance of a proxy class can be used as an instance of a target class. In general, the compile-time enhanced AOP framework is more advantageous in performance—because the runtime-enhanced AOP framework requires dynamic enhancements every time it runs.

Related