Followers

springAOP : @Around

The AspectJ around advice is applied before and after calling the actual business logic methods.

Create a class that contains actual business logic.

Employee.java
==========

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

Create the aspect class that contains around advice.

You need to pass the PreceedingJoinPoint reference in the advice method, so that we can proceed the request by calling the proceed() method.

TrackEmployee.java
=============

package com.mohan; 
 
import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.annotation.Around; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Pointcut;
 
@Aspect 
public class TrackEmployee{ 
   
    @Pointcut("execution(* Employee.*(..))") 
    public void abcPointcut(){} 
   
    @Around("abcPointcut()")
    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 create the Beans.xml file that defines beans.

Beans.xml
=======

<?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.xsd  
       http://www.springframework.org/schema/aop  
       http://www.springframework.org/schema/aop/spring-aop.xsd"> 
 
 
    <bean id="empBean" class="com.mohan.Employee">   </bean> 
    <bean id="trackEmp" class="com.mohan.TrackEmployee"></bean> 
     
    <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean> 
         
</beans>  

Now create the Test class that calls the actual methods.

Test.java
======
package com.mohan; 
 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
public class Test{ 
    public static void main(String[] args){ 
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); 
        Employee e = (Employee) context.getBean("empBean"); 
            e.msg();
            e.display();
       
    } 
}     

Expected Output

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  

No comments:

Post a Comment