Spring AOP:Aspect方法中的通过参数
题
我是春天aop的新手,并尝试使用aop:around
创建一个演示。
一个简单的bean类:
public class Employee {
private String name;
public String getName() {
System.out.println("Name: " + name);
return name;
}
public void setName(String name) {
this.name = name;
}
}
.
方面实现:
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");
}
}
}
.
上下文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());
}
}
.
我得到的o / p是:
打印前!!! 名称:XXX. 打印后!!! 员工名称:null
为什么最后一个null?
解决方案
一种方法是在这些变化中:
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!!!");
}
.
换句话说,您可以访问target
,该代码是要应用的AOP建议所代价的对象。 其他提示
Point.proceed() in the below code is responsible for actual exceution of the code and as your are using around advice you should capture the return value and return in the below method. As you are return nothing in the below method Its coming as null.
Please let me know if it doesn't work.I haven't tested It But It will Work.
public void performPrinting(ProceedingJoinPoint point){
try {
System.out.println("Before Printing!!!");
Object returnValue = point.proceed();
System.out.println("After Printing!!!");
} catch (Throwable e) {
System.out.println("Exception Printing");
}
return returnValue;
}
不隶属于 StackOverflow