Aspect Oriented Programming Using Spring AOP – An Introduction

by Veerasundar on April 12, 2009

in Java

As I’ve already told in my last article, The Aspect Oriented way of Programming, Spring provides it’s own API for incorporating AOP techniques to a Spring application. In addition to providing XML based configuration for AOP objects, Spring also supports the @AspectJ style configuration (the @AspectJ style is from the AspectJ project). Also note that, Spring supports AOP for method executions only. i.e. Spring AOP can execute your advice code only when the method execution takes place. But, if you have used AspectJ before, you could note that AspectJ supports adding advices to even property value changes, etc.

Enabling the @AspectJ style AOP in Spring:

I’ll first explain how to enable the @AspectJ support in your Spring application. I assume that you’ve already configured a Spring project (i.e. with necessary Spring JARs etc.).

  1. First, download the two JARs needed for @AspectJ support. They are aspectjrt.jar and aspectjweaver.jar. You can get these JARs from the Eclipse AspectJ project site. After downloading, place them in your project’s class path, typically in WEB-INF/lib folder.
  2. Once the JARs are in place, next we need to configure the Spring configuration file (the applicationContext.xml). Open the file and add the AOP name space and XSI Schema location like below:
    <beans
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
  3. Then, you need to add a line to the spring configuration file to enable the @AspectJ support.
    <aop:aspectj-autoproxy>
    </aop:aspectj-autoproxy>
    

Now the @AspectJ support is enabled in your Spring application. You can use annotations to specify your aspects and point cuts, here after.

In my next article, I’ll be explaining how to add a simple Aspect to a Hello World program.

{ 2 comments… read them below or add one }

Tsering Shrestha February 10, 2010 at 9:14 PM

If we are using spring-aop, I don’t think u need the aspectjrt jar as we are not using the AspectJ runtime. In fact even the aspectJ weaver is not used – the reference to the jar is only for the @AspectJ annotations. Spring will interpret those annotations and weave itself.

Reply

Veera February 11, 2010 at 6:19 AM

@Tsering Shrestha

Yes. You are correct. The aspectj jars are needed only if we are using AspectJ style annotations.

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: