Rick has posted 25 posts at DZone. You can read more from them at their website. View Full User Profile

An Introduction to Spring AOP

04.07.2009
| 80221 views |
  • submit to reddit

This article discusses Spring AOP in a tutorial format. It covers some of the newer features of Spring AOP like annotations, improved XML configuration and more. It builds on the DIIntroTutorial. It is meant as a simple introduction to AOP. Enough information so you –can use AOP on a project.

Spring 2.x AOP 

For some, AOP seems like voodoo magic. For others, AOP seems like a cureall. For now, let's just say that AOP is a tool that you want in your developer tool box. It can make seemingly impossible things easy.

The first time that I used AOP was with Spring's transaction management support. I did not realize I was using AOP. I just knew Spring could apply EJB-style declarative transaction management to POJOs. It was probably –three to six months before I realized that I was using was Spring's AOP support. The Spring framework truly brought AOP out of the esoteric closet into the main stream light of day.

You can think of AOP as a way to apply services (called cross-cutting concerns) to objects. AOP encompasses more than this, but this is where it gets used mostly in the main stream.

I've using AOP to apply caching services, transaction management, resource management, etc. to any number of objects in an application. It is not a panacea, but it certainly fits a lot of otherwise difficult use cases.

You can think of AOP as a dynamic decorator design pattern. The decorator pattern allows additional behavior to be added to an existing class by wrapping the original class and duplicating its interface and then delegating to the original. See this articdecorator pattern Decorator Pattern for more detail about the decorator design pattern.

Sample Application Revisited

or this introduction to AOP, let's take a simple example. Let's apply security services to our Automated Teller Machine example from the first DI example from the first tutorial in this series.

Let's say when a user logs into a system that a SecurityToken is created that carries the user's credentials, and before methods on objects get invoked, we want to check to see if the user has credentials to invoke these methods.

In a web application, you could write a ServletFilter,that stored this SecurityToken in HttpSession and then on every request retrieved the token from Session and put it into a ThreadLocal variable where it could be accessed from a SecurityService that you could implement.

Perhaps the objects that needed the SecurityService could access it as follows:

public void deposit(BigDecimal bd) {
                /* If the user is not logged in, don't let them use this method */
                if(!securityManager.isLoggedIn()){
                        throw new SecurityViolationException();
                }
                /* Only proceed if the current user is allowed. */

                if (!securityManager.isAllowed("AutomatedTellerMachine", operationName)){
                        throw new SecurityViolationException();
                }
                ...

                transport.communicateWithBank(...);
        }

In our ATM example, the above might work out well, but imagine a system with thousands of classes that needed security. Now imagine, the way we check to see if a user is logged is changed. If we put this code into every method that needed security, then we could possibly have to change this a thousand times if we changed the way we checked to see if a user was logged in.

What we want to do instead is to use Spring to create a decorated version of the –ATM? bean. The decorated version would add the additional behavior to the atm object without changing the actual implementation of the atm.

Spring does this by creating what is called an AOP proxy. An AOP proxy is like a dynamic decorator. Underneath the covers Spring can generate a class at runtime (the AOP proxy) that has the same interface as our AutomatedTellerMachine. The AOP proxy wraps our existing atm object and provides additional behavior by delegating to a list of method interceptors. The method interceptors provide the additional behavior and are similar to ServletFilters but for methods instead of requests.

Thus, before we added Spring AOP, our atm example was like Figure 1.

After we added AOP support, we now get an AOP proxy that applies the securityAdvice to the atm as show in figure 2.

 

 

You can see that the AOP proxy implements the AutomatedTellerMachine interface. When the client object looks up the atm and starts invoking methods instead of executing the methods directly, it executes the method on the proxy, which then delegates the call to a series of method interceptors called “Advice,” which eventually invoke the actual atm instance (now called atmTarget).

Published at DZone with permission of its author, Rick Hightower.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Michal Rembiszewski replied on Thu, 2009/04/16 - 3:12pm

I understand you wanted to give a simple example so the AOP concept is easier to grasp. As a side comment I often find myself trying to decide between using an aspect or a static decorator. While AOP seems more versatile at a first glance, it makes your code much more annoying to debug, both interactively and by making stacktraces look ugly. Therefore I usually use it only if the new functionality is required in more than one class (otherwise it isn't really a cross-cutting concern). In case presented in the example I would go with old-style static decorator which is easy enough to configure using spring.

Walter Bogaardt replied on Tue, 2009/05/26 - 11:17am

Simple to understand article. There is always a decision that has to be made in choosing AOP over other designs in your applications. Architecture can be pragmatic or dogmatic as I've seen so much of as technologies evolve and new terms are slapped. I found it useful for creating container independent implementation of persistable jmx beans, transactional support is another area. Yet in all cases it sometimes makes debugging problems a pain, but once you have a solid aspect usually life is good.

Jeroen Rosenberg replied on Fri, 2010/05/07 - 3:16am

Nice article! Recently I've uploaded a presentation on Spring AOP . Might be interesting for you.

Krishnendu Sardar replied on Wed, 2012/09/05 - 5:02am

Hi Can you please provide link to download the whole project?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.