Aspect Oriented Programming Using Spring AOP – An Introduction [Part 2]

by Veerasundar on April 14, 2009

in Java

In my last article, I’ve explained how to enable @AspectJ support in a Spring application. And today, in the last post of the series, I’ll show you a small example code that uses the AOP concepts for logging method calls. Before reading this post, I’ll suggest you to read the basics of AOP and Using AOP in Spring posts which will help you to understand AOP better.

Spring AOP – Hello World Example:

The below steps explains how to get started with the Hello World example using Spring AOP for logging the method call details, when ever the HelloWorld class’s methods are called by the external world.

  1. Firstly, you need to set up the @AspectJ support in Spring by adding the required JARs and enabling the @AspectJ in the Spring configuration file (for example, applicationContext.xml). Please read this post how to do this.
  2. Once the environment is setup, next task will be to create the world fame POJO class ‘Hello World’. Below is the code for the same.
    package com.veerasundar.aop.demo
    
    public class HelloWorld{
       public void sayHello(String name){
          System.out.println("Hello " + name);
       }
    
       public static void main(String args[]){
          HelloWorld hw = new HelloWorld();
          hw.sayHello();
       }
    }
    
  3. Now we will add our logging code, using AOP, so that whenever the method sayHello is called, that call will be logged. Below is our Aspect code.
    package com.veerasundar.aop.aspects
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Pointcut;
    import org.aspectj.lang.annotation.Before;
    
    @Aspect
    public class HelloWorldLoggerAspect{
       @Pointcut("execution(* com.veerasundar.aop.demo.*.*(..))")
        public void helloWorldMethods(){}
    
       @Before("helloWorldMethods()")
       public void logMethodCall(){
          System.out.println("The Hello World Method has been called.");
       }
    }
    

    So, what are we doing here in this HelloWorldLoggerAspect? In the code,

    1. After the package declaration, we are importing the AspectJ related classes to use in our code.
    2. Then we are declaring that the class HelloWorldLoggerAspect is an aspect using the @AspectJ annotation. (Note: to enable this kind of annotation based configuration, you need to have AspectJ jars in your classpath and you need to configure the Spring configuration file properly. See this article enabling @AspectJ in Spring AOP for more details.)
    3. Then inside the class, we are declaring pointcut which matches all the methods inside the com.veerasundar.aop.demo package. So, all the methods inside the mentioned package will be matched for the helloWorldMethods pointcut (note that, Spring supports only method matching in pointcut definitions). And the pattern inside the @Pointcut definition is AspectJ style pattern. Please refer AspectJ documentation for more information on the same. In our code, we are saying that “what ever the methods with any return type and which takes any number of parameters and which resides inside the com.veerasundar.aop.demo package” match it as helloWorldMethods pointcut.
    4. Finally in using the @Before annotation, we are defining our Advice code, which will be executed before the helloWorldMethods(). i.e. When ever the methods which are matching the helloWorldMethods pointcut are called, our logMethodCalls will be executed first and then the control will go to the actual function called. This process is called as Weaving and the Spring AOP takes care of it.
  4. There is one more step that needs to be done – configuring the spring configuration file. Add the below lines to your Spring config file, to declare the aspect HelloWorldLoggerAspect.
    <aop:aspectj-autoproxy/> <bean id="helloWorldLoggerBean" class="com.veerasundar.aop.aspects.HelloWorldLoggerAspect" />
    
  5. With that configurations are all done, now when ever a call made to the sayHello() method inside the HelloWorld object, the call will be logged (i.e. a message will appear on the console. in real world applications, this will a be log message).

So, with this post, I’m concluding the AOP series. I hope that the series would be useful to you to have basic understanding about the AOP. Please let me what do you think about this series through your comments.

{ 19 comments… read them below or add one }

rance April 15, 2009 at 11:26 AM

Holy crap! You can actually do logging with an Aspect?
I’ve never heard of such a thing.

Kudos for giving us such a unique application!
You are the man!

Reply

Veerasundar April 15, 2009 at 3:53 PM

Hi Rance,

A lot more can be done using AOP, than just logging. For example, checking for authentication before accessing some service methods, profiling the method execution timings, etc.

Logging is just an example, I took for this tutorial. :)

Reply

Nisha May 6, 2009 at 5:18 PM

Explained very well by giving suitable example.You make it easy to understand.Kindly explain,what else AOP can do other than logging.

Reply

Amerish June 4, 2009 at 10:37 AM

Hey Veera, nice example…..

can you provide some more info of usign AspectJ for authorization of service layer methods using Spring IOC. We faced certain issues. It will be of great help, if you provide any pointers.

Thanks
Amerish

Reply

Veera June 4, 2009 at 12:33 PM

Thanks Amerish. I’ll try provide some more examples on the authorization front.

Reply

kumar June 19, 2009 at 4:42 PM

hi veera,

Thanks for the tutorial. i was struggling to understand this concept. At last it was clear. It would be nice that if you can come up with some examples of other concerns of the AOP like authorization, transcation.

thanks & regards
Kumar

Reply

Veera June 21, 2009 at 7:05 AM

Thanks for the feedback Kumar. Will definitely give more example of AOP.

Reply

kumar June 21, 2009 at 4:14 AM

Hi veera,

I worked on this example what you have shown in this post. But i can’t get the logging output to my console. The output i got is just

“Hello Kumar”

but the actuall o/p should be like this i think
———————————–
The Hello World Method has been called.
Hello Kumar.
———————————–
please advice me in this

thanks
kumar

Reply

Veera June 21, 2009 at 7:03 AM

Hi Kumar,

Please ensure that,
1. U have the AspectJ jars in your classpath
2. U have enabled AspectJ support in your application context path
3. U have given the correct pointcut definition.

Reply

kumar June 21, 2009 at 1:03 PM

Hi Veera,

Thanks for your prompt reply. I have added my programs i am wondering can find any errors in this
————————————-
package com.gtsv.helloworlddemo;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class HelloWorld
{
public void sayHello(String name){
System.out.println(“Hello ” + name);
}

public static void main(String args[])
{
FileSystemResource fsr = new FileSystemResource(“beans.xml”);
BeanFactory factory = new XmlBeanFactory(fsr);
HelloWorld hw = new HelloWorld();
hw.sayHello(“kumar”);
}
}
————————————-
package com.gtsv.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class HelloWorldLoggerAspect
{
@Pointcut(“execution(* com.gtsv.aop.*.*(..))”)
public void helloWorldMethods(){}

@Before(“helloWorldMethods()”)
public void logMethodCall(){
System.out.println(“The Hello World Method has been called.”);
}
}
————————————-

————————————-
jar file in application
1.aspectjweaver.jar
2.aspectjrt.jar
3.spring.jar
4.common-logging.jar

can you please help me in this issue.
thanks
kumar

Reply

Veera June 21, 2009 at 2:59 PM

Hi Kumar,

Few things I noticed in your code:

1) Have you declared the @AspectJ support in your ‘beans.xml’ file ?
2) You are creating the HelloWorld object using ‘new’ keyword.

//HelloWorld hw = new HelloWorld();//

but, you should be getting the HelloWorld instance from your spring context. eg;

factory.getBean(helloworldbean);

Spring applies AOP to the objects which it is managing.

Reply

karunakar June 24, 2009 at 7:02 PM

hi veera…am new to spring and am willing to start learning creating my own application.can you suggest me a way of doing this.

Am familiar with struts,ejb,webservices,hibernate.please guide me in this regard

Reply

Srikanth October 29, 2009 at 11:02 AM

Hi,

It was good posting, Since i am new to the springs framework i didnt understand [@Pointcut("execution(* com.veerasundar.aop.demo.*.*(..))")].

Regards,
Sri

Reply

Veera October 29, 2009 at 11:43 AM

thanks Srikanth.

the pointcut definition tell the Spring AOP to intercept at that point. For example, in the above definition, AOP inserts our code when ever the methods inside the com.veerasundar.aop.demo gets executed.

I hope I answered your question. Do let me know if it needs further explanation.

Reply

Veera October 30, 2009 at 12:47 PM

Hi Srikanth,

To explain that point further, I’m quoting from Spring AOP’s documentation:

Spring AOP only supports method execution join points for Spring beans, so you can think of a pointcut as matching the execution of methods on Spring beans. A pointcut declaration has two parts: a signature comprising a name and any parameters, and a pointcut expression that determines exactly which method executions we are interested in. In the @AspectJ annotation-style of AOP, a pointcut signature is provided by a regular method definition, and the pointcut expression is indicated using the @Pointcut annotation (the method serving as the pointcut signature must have a void return type).

so that method is just a signature. It need not to have a function body!

Reply

Priya January 11, 2010 at 11:47 AM

Hi,

I implemented your sample,but while configuring the application-context.xml,I’m getting

I’m getting Remote location not loaded error.

I added the Spring-context.jar in my classpath

Reply

Priya January 11, 2010 at 11:54 AM

Kindly tell me what wrong with my cod

Helloworld.java
—————————————-

public class HelloWorld{

static ApplicationContext ctx;
static HelloWorld helloWorld;

public void sayHello(String name){
System.out.println(“Hello ” + name);
}

public static void main(String args[]){

ApplicationContext context = new ClassPathXmlApplicationContext(“applicationContext.xml”);
helloWorld = (HelloWorld)context.getBean(“helloWorldLoggerBean”);
System.out.println(“HelloWorld:”+helloWorld);
HelloWorld hw = new HelloWorld();
hw.sayHello(“Priya”);
}
}

@Aspect
public class HelloWorldLoggerAspect{
@Pointcut(“execution(* test.*.*(..))”)
public void helloWorldMethods(){}
@Before(“helloWorldMethods()”)
@After(“helloWorldMethods()”)
public void logMethodCall(){
System.out.println(“The Hello World Method has been called.”);
}
}

application-context.xml

I’m getting a warning message in the application-context.xml.Remote location could not be loaded.

I added the Spring-context.jar in my classpath

Kindly reply .

Reply

Veera January 11, 2010 at 3:10 PM

Hi Priya,

Will get back to you shortly with a working solution.

Reply

Veera January 12, 2010 at 1:34 PM

Hi Priya,

you can look at this example for a better explanation on Spring AOP – http://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/

Reply

Leave a Comment

Previous post:

Next post: