logo

Spring AOP With AspectJ Xml Configuration Example


Show

In the Spring framework, An Aspect-Oriented Oriented Programming (AOP) can be achieved by using the aspects, advice, and pointcuts in the XML file. Spring AOP XML-based configuration can be used as an alternative to the annotation-based examples. Through the AspectJ libraries, you can declare aspect, pointcut, etc using the XML file. The Syntax that is used in the AspectJ Xml Configuration includes an aspect where an element is used to declare this configuration. Here, the ref attribute is used for bean reference. An expression element in Pointcut is used for matching the Joinpoint. Here, the tag that is used to declare an aspect is <aop: aspect>

Now, we will study various XML elements that are used to define advice.

Aop: before> It is used before the actual business logic method is invoked.

Aop: after> It is applied after invoking the actual business logic method.

Aop: after-returning> It is applied after calling the actual business logic methods. By using After advice, we can intercept the return value.

Aop: around> This element is applied around (before and after) calling the actual business logic method.

Aop: after-throwing> As the name suggests, this element is applied if the actual business logic method throws an exception.

Now, we will briefly introduce these elements with the use of AspectJ Xml Configuration examples.

aop: before Example

The Before Advice element in Aspect-Oriented Programming is used before we call the actual business logic method. In Spring AOP, it is aimed to get the cross-cutting of concerns. Under this type of advice, you can accomplish the tasks like conversion, authentication, etc.

Now let’s see how can we use this element in our example:

First, we create an Operation.java class that consists of the actual business logic.

package com.Intellinuts;  
public class Operation{  
    public void msg(){System.out.println("msg method invoked");}  
    public int m(){System.out.println("m method invoked");return 2;}  
    public int k(){System.out.println("k method invoked");return 3;}  
}

Then, we create an aspect class TrackOperation.java, that includes the before advice.

package com.Intellinuts;  
import org.aspectj.lang.JoinPoint;  
public class TrackOperation{  
    public void myadvice(JoinPoint jp)//it is advice  
    {  
        System.out.println("additional concern");  
        //System.out.println("Method Signature: " + jp.getSignature());  
    }  
}

In our XML Configuration file that is applicationContext.xml, aop: before the method is used as myadvice and a pointcut reference as pointCutBefore.

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/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-3.0.xsd   
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">  

<aop:aspectj-autoproxy />  
<bean id="opBean" class="com.Intellinuts.Operation"> </bean>  
<bean id="trackAspect" class="com.Intellinuts.TrackOperation"></bean>  
<aop:config>  
  <aop:aspect id="myaspect" ref="trackAspect" >  
     <!-- @Before -->  
     <aop:pointcut id="pointCutBefore" expression="execution(* com.Intellinuts.Operation.*(..))" />  
     <aop:before method="myadvice" pointcut-ref="pointCutBefore" />  
  </aop:aspect>  
</aop:config>    
</beans>  

Now, we will proceed to call the actual method by creating a class named Test.java that gets the bean details from the configuration file and displays the output.

package com.Intellinuts;  

import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
public class Test{  
    public static void main(String[] args){  
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
        Operation e = (Operation) context.getBean("opBean");  
        System.out.println("calling msg...");  
        e.msg();  
        System.out.println("calling m...");  
        e.m();  
        System.out.println("calling k...");  
        e.k();  
    }  
}  

The output of the above program is:

calling msg...  
additional concern  
msg() method invoked  
calling m...  
additional concern  
m() method invoked  
calling k...  
additional concern  
k() method invoked 

The output that illustrates above mentioned that the phrase additional concern is displayed before the msg(), m(), and k() method is invoked.

aop: After Example

This advice of the AspectJ AOP in Spring is applied after calling the actual business logic methods to ensure that the advice runs after the method execution. In the XML configuration of AspectJ, it is used by <aop:after> tag. We can use this advice to maintain activities like a log, security, notification, etc.

Before we go to the example that uses aop: after advice, we assume that Operation.java, TrackOperation.java, and Test.java files are the same as given in aop: before example.

So we need to create an applicationContext.xml file to define the beans.

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/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-3.0.xsd   
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">  
<aop:aspectj-autoproxy />  
<bean id="opBean" class="com.Intellinuts.Operation"> </bean>  
<bean id="trackAspect" class="com.Intellinuts.TrackOperation"></bean>  
<aop:config>  
  <aop:aspect id="myaspect" ref="trackAspect" >  
     <!-- @After -->  
     <aop:pointcut id="pointCutAfter" expression="execution(* com.Intellinuts.Operation.*(..))" />  
     <aop:after method="myadvice" pointcut-ref="pointCutAfter" />  
  </aop:aspect>  
</aop:config>  

</beans>  

Here comes the output of the above file:

calling msg...  
msg() method invoked  
additional concern  
calling m...  
m() method invoked  
additional concern  
calling k...  
k() method invoked  
additional concern 

On the contrary to the previous example where the additional concern is printed after calling msg(), m(), and k() methods, here it does it differently. You can see that the phrase additional concern is printed just after each time we call the msg(), m(), and k() methods respectively.

aop: After-Returning Example

After-returning is advice that comes in Spring AOP, which is called after the normal and complete execution of a join point. It cannot be invoked in case an exception is being thrown. This advice runs when a matched method execution normally returns a value. We can get the result in After-returning advice. It is used as <aop:after-returning> tag.

To know the use of after-running advice, we will create the class named Operation.java that includes the business logic.

package com.Intellinuts;  
public class Operation{  
    public int m(){System.out.println("m() method invoked");return 2;}  
    public int k(){System.out.println("k() method invoked");return 3;}  
}  

In our next step, we create the class named TrackOperation.java that uses after-returning advice.

package com.Intellinuts;  

import org.aspectj.lang.JoinPoint;  
public class TrackOperation{  
    public void myadvice(JoinPoint jp,Object result)//it is advice (after advice)  
    {  
        System.out.println("additional concern");  
        System.out.println("Method Signature: " + jp.getSignature());  
        System.out.println("Result in advice: "+result);  
        System.out.println("end of after returning advice...");  
    }  
}  

Now, we create the applicationContext.xml file for bean definition.

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/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-3.0.xsd   
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">  
<aop:aspectj-autoproxy />  
<bean id="opBean" class="com.Intellinuts.Operation"> </bean>  
<bean id="trackAspect" class="com.Intellinuts.TrackOperation"></bean>  
<aop:config>  
  <aop:aspect id="myaspect" ref="trackAspect" >  
     <!-- @AfterReturning -->  
     <aop:pointcut id="pointCutAfterReturning" expression="execution(* com.Intellinuts.Operation.*(..))" />  
     <aop:after-returning method="myadvice" returning="result" pointcut-ref="pointCutAfterReturning" />  
  </aop:aspect>  
</aop:config>  

</beans>  

Now, we will create the Test.java class that calls the actual methods by getting the bean information from the applicationContext.xml file and prints the return value.

package com.Intellinuts;  
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
public class Test{  
    public static void main(String[] args){  
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
        Operation e = (Operation) context.getBean("opBean"); 
        System.out.println("calling m...");  
        System.out.println(e.m());  
        System.out.println("calling k...");  
        System.out.println(e.k());  
    }  
}  

Finally, you will see the output as mentioned below:

calling m...  
m() method invoked  
additional concern  
Method Signature: int com.Intellinuts.Operation.m()  

Result in advice: 2  
end of after returning advice...  
2  
calling k...  
k() method invoked  
additional concern  
Method Signature: int com.Intellinuts.Operation.k()  

Result in advice: 3  
end of after returning advice...  
3  

Here, you can see that the value that is returned is displayed two times by TrackOperation class and Test class respectively.

aop: Around

The around the advice of AspectJ is applied before and after calling the actual business logic methods to ensure that advice can run before and after the execution of these methods. In the AspectJ XML Configuration, it is declared as <aop:around> tag. Regarded as the most powerful advice in Spring AOP, it can be executed before and after the execution of a join point.

Now we create a class named Operation.java and provide an actual business logic in it.

package com.Intellinuts;  
public class Operation{  
    public void msg(){System.out.println("msg() is invoked");}  
    public void display(){System.out.println("display() is invoked");}  
} 

Now we will create an aspect class named TrackOperation.java class. It is a requirement to pass the ProceedingJoinPoint reference in the advice method to make way for the request of calling the proceed() method.

package com.Intellinuts;  
import org.aspectj.lang.ProceedingJoinPoint;  
public class TrackOperation  
{  
    public Object myadvice(ProceedingJoinPoint pjp) throws Throwable   
    {  
        System.out.println("Additional Concern Before calling actual method");  
        Object obj=pjp.proceed();  
        System.out.println("Additional Concern After calling actual method");  
        return obj;  
    }  
}  

Now, we will create the file named applicationContext.xml that contains the bean definition and which defines the around advice as myadvice, a pointcut reference as pointCutAround.

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/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-3.0.xsd   
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">   

<aop:aspectj-autoproxy />  
<bean id="opBean" class="com.Intellinuts.Operation"> </bean>  
<bean id="trackAspect" class="com.Intellinuts.TrackOperation"></bean>  
<aop:config>  
  <aop:aspect id="myaspect" ref="trackAspect" >  
     <!-- @Around -->  
     <aop:pointcut id="pointCutAround" expression="execution(* com.Intellinuts.Operation.*(..))" />  
     <aop:around method="myadvice" pointcut-ref="pointCutAround" />  
  </aop:aspect>  
</aop:config>  
</beans> 

Now to call the actual methods and print the output of the returned value, we will create the Test.java class. This class will get the bean information from the applicationContext.xml file and display the returned value by calling the display() method.

package com.Intellinuts;  
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
public class Test{  
    public static void main(String[] args){  
        ApplicationContext context = new classPathXmlApplicationContext("applicationContext.xml");  
        Operation op = (Operation) context.getBean("opBean");  
        op.msg();  
        op.display();  
    }  
}  

The output of the above program is:

Additional Concern Before calling actual method  
msg() is invoked  
Additional Concern After calling actual method  
Additional Concern Before calling actual method  
display() is invoked  
Additional Concern After calling actual method

In the output of the above program, we can see that the term ‘additional concern’ is printed before and after calling msg() and display methods.

aop: After-Throwing Example

It is a type of AspectJ advice that clears the way for an advice to run if an exception is thrown by the method. After-throwing will get executed after the Join Point fails to complete normally and throws an exception.

In this example, we will use after-throwing to print the exception in the TrackOperation class. To learn this, we will create a class named Operation.java that contains the business logic.

package com.Intellinuts;  
public class Operation{  
    public void validate(int age)throws Exception{  
    if(age<18){  
        throw new ArithmeticException("Not valid age");  
    }  
    else{  
        System.out.println("Thanks for vote");  
    }  
    }  

} 

Now, we will create the aspect class named TrackOperation.java, which includes the after-throwing advice. Here it is compulsory to pass the throwable reference as well so that the exception can be intercepted.

package com.Intellinuts;  
import org.aspectj.lang.JoinPoint;  
public class TrackOperation{  
    public void myadvice(JoinPoint jp,Throwable error)//it is advice  
    {  
        System.out.println("additional concern");  
        System.out.println("Method Signature: " + jp.getSignature());  
        System.out.println("Exception is: "+error);  
        System.out.println("end of after throwing advice...");  
    }  
}  

In the applicationContext.xml, we use aop:after-throwing method as ‘myadvice’, Pointcut reference as ‘pointCutAfterThrowing’ along with the bean definition.

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/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-3.0.xsd   
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">  
<aop:aspectj-autoproxy />  
<bean id="opBean" class="com.Intellinuts.Operation"> </bean>  
<bean id="trackAspect" class="com.Intellinuts.TrackOperation"></bean>  

<aop:config>  
  <aop:aspect id="myaspect" ref="trackAspect" >  
     <!-- @AfterThrowing -->  
     <aop:pointcut id="pointCutAfterThrowing" expression="execution(* com.Intellinuts.Operation.*(..))" />  
     <aop:after-throwing method="myadvice" throwing="error" pointcut-ref="pointCutAfterThrowing" />  
  </aop:aspect>  
</aop:config>  

</beans>  

Our next step will be to create the Test.java class that calls the actual methods after getting the bean information from the applicationContext.xml file.

package com.Intellinuts;  

import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
public class Test{  
    public static void main(String[] args){  
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
        Operation op = (Operation) context.getBean("opBean");  
        System.out.println("calling validate...");  
        try{  
            op.validate(19);  
        }catch(Exception e){System.out.println(e);}  
        System.out.println("calling validate again...");  

        try{  
            op.validate(11);  
        }catch(Exception e){System.out.println(e);}  
    }  
}  

The displayed output of the above program is:

calling validate...  
Thanks for vote  
calling validate again...  
additional concern  
Method Signature: void com.Intellinuts.Operation.validate(int)  
Exception is: java.lang.ArithmeticException: Not valid age  
end of after throwing advice...  
java.lang.ArithmeticException: Not valid age