Java SpringAOP:如何将参数从被调用方法传递到通知方法?
我正在设计一个系统,需要将参数从被调用的方法传递到advice方法。我提供了一个简单的代码来阐明这一点- //AOPMain.java:Java SpringAOP:如何将参数从被调用方法传递到通知方法?,java,spring,spring-aop,Java,Spring,Spring Aop,我正在设计一个系统,需要将参数从被调用的方法传递到advice方法。我提供了一个简单的代码来阐明这一点- //AOPMain.java: public class AOPMain { public static void main(String[] args) { ApplicationContext cxt = new ClassPathXmlApplicationContext("spring.xml"); Employee emp = cxt.getBean("empl
public class AOPMain {
public static void main(String[] args) {
ApplicationContext cxt = new ClassPathXmlApplicationContext("spring.xml");
Employee emp = cxt.getBean("employee", Employee.class);
emp.sayHello();
}
}
//Employee.java:
public class Employee {
private String name;
public String getName() {
System.out.println("getName");
return name;
}
public void setName(String name) {
System.out.println("setName");
this.name = name;
}
public void sayHello() {
System.out.println("Hello World!");
//How to pass argument to afterAdvice
}
}
//Logging.java:
@Aspect
public class Logging {
@Pointcut("execution(public void sayHello())")
public void doSomething(){}
@After("doSomething()")
public void afterAdvice() {
System.out.println("After Advice");
//Depending on the argument passed, send notification
}
}
我如何设计这个系统?我知道有一些方法可以使用&&args()将参数从AOPMain本身传递到advice方法,但我找不到任何用于此特定问题的示例代码
我知道它违反了基本的设计原则,即通知方法不是松散耦合的。那么Spring支持这一点吗
提前谢谢
@After("doSomething()")
public void afterAdvice(JoinPoint joinPoint) {
System.out.println("After Advice");
//joinPoint.getArgs();
//Depending on the argument passed, send notification
}
不能解决你的问题吗?请参阅了解更多信息。从建议的方法中获取信息有两种方法:
- 让它返回一个值,并在通知中使用该返回值:
public Arg sayHello() { System.out.println("Hello World!"); //How to pass argument to afterAdvice Arg arg = ...; return arg; } @AfterReturning(pointcut="doSomething()", returning="retval") public void afterAdvice(Object retval) { System.out.println("After Advice"); // use retval here ... }
- 使用连接点访问调用方法的原始对象,并将arg作为对象属性传递:
只有当建议的对象是statefull时,此选项才有意义-不要考虑在共享对象的服务或控制器上使用它public void sayHello() { System.out.println("Hello World!"); //How to pass argument to afterAdvice this.arg = ...; } @After("doSomething()") public void afterAdvice(JoinPoint jp) { System.out.println("After Advice"); Employee emp = (Employee) jp.getTarget(); // use emp.arg here ... }
afterAdvice
)应用到第一级方面(doSomething
)?嗨@Ralph,谢谢你的回复。实际上我正在设计一个通知系统。main方法将调用另一个类中的checkThreshold方法,如果达到阈值限制,则将使用适当的字符串参数自动调用advice方法。通知方法将向外部引擎发送正确的通知。因此,我被困在如何实现这一壮举上。嗨@Lovababu,我已经检查了您提供的示例。但是在logBefore()方法中,我们正在访问最初传递给addCustomer()方法的参数(从main)。但我想将参数(字符串变量)从addCustomer()传递到logBefore()。它可以通过joinPoint.getArgs()实现吗?让我试试。嗨!谢谢!你的建议解决了我的问题!我发现还有一种不同的方式。我可以抛出一个自定义异常,而不是从adviced方法返回一个值,在advice方法中我可以使用afterhrowing子句。因此,建议和建议方法可以沟通的两种方式是事后返回和事后补救。谢谢你的帮助!