gpt4 book ai didi

java - Spring AOP : Passing parameter in aspect method

转载 作者:行者123 更新时间:2023-12-01 12:54:02 31 4
gpt4 key购买 nike

我是 Spring 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>

应用程序.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打印后!!!员工姓名:空

为什么最后一个为空?

最佳答案

一种方法是进行以下更改:

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!!!");
}

换句话说,您可以访问目标,它是为应用 AOP 建议而被代理的对象。

关于java - Spring AOP : Passing parameter in aspect method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24022295/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com