Implementing AOP in Spring

Aspect Oriented Programming (AOP) used to be a bit complex due to the exposure of the low level constructs to the Spring developer. But that's changed; both Spring and AOP have evolved. Manoj Debnath offers a canonical explanation of AOP and on how to implement it in Spring.

Aspect Oriented Programming (AOP) has always been a fundamental component of the Spring framework. This programming model used to be a bit complex due to the exposure of the low level constructs to the Spring developer. Perhaps, for this reason programming Spring AOP rested in the hands of advanced developers. Lately, a lot has changed - Spring has evolved and so has AOP. In this article I will resort to a canonical explanation of AOP and on how to implement it in Spring. So, before getting hands on - a little detour.

Functional Programming

In case of Functional Programming (FP), problems are broken down into a module of functions, which carry out a particular unit of work. Each function talks to another through function calls. The whole concept is to separate the problem domain with a cohesive module of function.

Now, imagine a situation of a complex network of function calls. You get a bowl of spaghetti code!

Spaghetti code

Object Oriented Programming

In Object Oriented Programming (OOP) the thought process of designing an application gets a paradigm shift. Different tasks are no longer modeled as a unit of function but rather as an individual object, which mirrors a different entity in a problem space.

As a result designing complex code got a much cleaner separation of concern. But still...

A couple of problems persist.

A situation arose where not all of the tasks can be classified into an object or implementing such an object does not adhere to the business concern, per se.

Suppose there is a common procedure used by some/all of the objects, such as logging a message. Now, to implement that, one has to either define logMessage as the member function in each object that wants to log a message or create a separate Logger class with logMessage as a member static/non-static function, so that it can be used in the way the programmer wants either by inheriting or creating new Logger object or simply calling the static member function or by using dependency injection functionality through Spring.

Whatever the case, it is not a very good idea to design in the manner described. In the above case, observe that the most used object in the arena is actually the most unimportant one. The Logger object adds nothing to the business concern. It only supports the cause yet it gets the maximum attention from the object interaction. OOP is just fine but another level of modularity is sought to address this issue of pure separation of cross-cutting concern.

Aspect Oriented Programming

AOP leveraged the modularity of OOP paradigm to a whole new level. It provides separation of crosscutting concerns by introducing a new unit of modularization called an aspect. The aspect focuses on a particular crosscutting functionality and does not burden the core business classes of the application with crosscutting concerns. This is done with aspect weaver that composes the final system by combining core classes and crosscutting aspects through a process called weaving. AOP further refurbished OOP, which are easier to design, implement, and maintain.

AOP in Spring Framework

The core areas of Spring are dependency injection, enterprise service abstraction and aspect oriented programming. Dependency injection allows disparate components to be wired into a fully working application in declarative manner, enterprise service abstraction isolates stable application logic from volatile infrastructure code and AOP lets you separate the implementation of cross-cutting concerns from business concerns. This trio can be well integrated to offer a compelling solution in Spring.

AOP implementation in Spring

Software Dependencies:

For Aspectj programming

Aspectj: Aspectj compiler produces programs for any version of the Java platform, but the compiler itself requires Java2 (1.4 or later) to run.

Cglib: Code Generation Library, used to extend JAVA classes and implements interfaces at run time.

Aopalliance : A set of interfaces used by multiple frameworks such as Guice and Spring.

LogginAspect class demonstrates the implementation of AOP in Spring. Note that it is nothing more than a simple POJO with the annotation @Aspect. Inside this class one can write as many advices (advice is a AOP terminology that means nothing more than a function prefixed with AOP annotation) as one wants to using the annotation like @Before, @After, @Within, @Around, @Pointcut etc.

@Before annotation simply means that beforeAdvice advice would run before any public String getName() function is executed. There are other variations of @Before annotation such as:

@Before("execution(public
String org.simpleaop.Employee.getName())")

The difference is that the advice now runs only before getName function of Employee class.

Using wild cards:

@Before("execution(public * get*())")

calls any public function with any return type with no argument but function name prefixed by 'get'.

@Before("execution(public * get*(..))")

calls any public function with any return type with zero/more argument but function name prefixed by 'get'.

@Before("execution(public * get*(*))")

calls any public function with any return type with one/more argument but function name prefixed by 'get'.

For more examples and explanation visit the Spring aspect-oriented programming documentation.

AOP Usage

There are several occasions where AOP can be very handy, some of the most common use cases can be Logging and Profiling.

AOP can be very useful in transaction management where request processing methods can be wrapped using @Around advice where transactions can be rolled back immediately on failure.

An access control or security mechanism can be built with @Before advice and verify the access credentials before letting one in.

Exception wrapping can be done when business methods throw an exception. The @After throwing advice can be utilized to handle the situation. For example, if one wants to wrap all SQLException into data access layer exception and throw it back to service layer without handling it in every DAO method.

There are innumerable such AOP usages. The citations above just scratche the surface.

Conclusion

Spring is a popular lightweight framework for enterprise applications. AOP system based on interceptors and the proxy design pattern is included in the framework to replenish the needs of enterprise applications. Prior to Spring 2.0, Spring AOP was more complex. The new programming model based on AspectJ offers a better programming experience and enables programmers to write better code and customize aspects without difficulty. Once one has a fair grasp on the concept of dependency injection and AOP, the learning curve of Spring implementation of aspect-oriented programming in almost flat.

Advertiser Disclosure:
Some of the products that appear on this site are from companies from which QuinStreet receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. QuinStreet does not include all companies or all types of products available in the marketplace.