Search code examples
javaspringaspectjspring-3

Spring AOP: Passing parameter in aspect method


I am new to Spring AOP and trying to create a demo using aop:around.

A simple bean class:

public class Employee {

private String name;
public String getName() {
    System.out.println("Name: " + name);
    return name;
}
public void setName(String name) {
    this.name = name;
}
}

Aspect implementation:

public class PrintingAspect {

public void performPrinting(ProceedingJoinPoint point){
    try {
        System.out.println("Before Printing!!!");
        point.proceed();        
        System.out.println("After Printing!!!");
    } catch (Throwable e) {         
        System.out.println("Exception Printing");
    }
}
}

Context XML:

<bean id="aspect" class="com.aop.aspect.PrintingAspect">        
</bean>    
<bean id="employee" class="com.aop.model.Employee">
    <property name="name" value="XXX"></property>
</bean>
<aop:config>
    <aop:pointcut id="empName" expression="execution(* com.aop.model.Employee.getName(..))"/>
    <aop:aspect ref="aspect">            
        <aop:around pointcut-ref="empName" method="performPrinting"/>
    </aop:aspect>
</aop:config>

App.java

public class App 
{
public static void main( String[] args )
{
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
    Employee empl = (Employee)context.getBean("employee");
    System.out.println("Employee Names: " + empl.getName());
}
}

The o/p I am getting is:

Before Printing!!! Name: XXX After Printing!!! Employee Names: null

Why is the last one null ?


Solution

  • One way to do it is with these changes:

    XML:

    <aop:pointcut id="empName"
            expression="execution(* com.example.Employee.getName(..))" />
    

    Java:

    public void performPrinting(ProceedingJoinPoint jp) { // Here empl is coming null
        System.out.println("Before Printing!!!");
        System.out.println(((Employee)jp.getTarget()).getName()); // empl is coming as NULL
        System.out.println("After Printing!!!");
    }
    

    In other words, you get access to the target which is the object that is being proxied for the AOP advice to be applied.