英文:
Spring AOP: exchanging information between methods
问题
假设我有一个名为 MyServlet 的类,其目的是响应用户请求:
@Component
public class MyServlet
{
	public void accept(String clientName, int clientID)
    {
		System.out.println("Processing client:" + clientName + " with ID: " + clientID);
	}
}
一般来说,为了调试我们的应用程序,在尝试服务用户请求之前,我们可能希望记录用户请求的情况。因此,我希望在调用 accept() 之前能够透明地发生这种行为。对于这种情况,一个名为 Helper 的类可以提供日志记录功能,并且我们将使用 @Before 进行修饰:
@Aspect
@Component
@EnableAspectJAutoProxy
public class Helper
{
	@Before("execution(public void show())")
	public void log()
    {
		System.out.println("Logging data...");
	}
}
但是,我希望能够获取传递给 accept() 的信息(在这种情况下是一个 String 和一个 int),并将其传递给 log(),因为这将允许我将用户及其ID精确记录到任何我使用的日志存储中。我如何实现这一点?
英文:
Suppose that I have a class called MyServlet, whose purpose is to respond to a user request:
@Component
public class MyServlet
{
	public void accept(String clientName, int clientID)
    {
		System.out.println("Processing client:" + clientName + " with ID: " + clientID);
	}
}
Generally speaking, serving the request of a user might be something we want to log before we attempt it to debug our application. So I would really like it if I could have this behavior happen transparently before accept() is ever called. For this person, a Helper class can provide a logging functionality, which we will decorate with @Before:
@Aspect
@Component
@EnableAspectJAutoProxy
public class Helper
{
	@Before("execution(public void show())")
	public void log()
    {
		System.out.println("Logging data...");
	}
}
But it would be really useful for me to be able to get the information that is provided to accept() (in this case, a String and an int) and pass it into log(), since it would allow me to log exactly the user and their ID into whatever logging store I use. How can I achieve this?
答案1
得分: 1
以下是翻译好的部分:
你可以通过注入 JoinPoint 实例并在其上调用 getArgs() 方法来访问代理方法的参数。下面是示例代码片段。
@Before("execution(* com.sample.SomeClass.doSometning(..))")
public void doSomethingBefore(JoinPoint joinPoint) {
   Object[] args = joinPoint.getArgs();
   for (Object arg: args) {
       // 对参数进行任何想做的操作
   }
}
英文:
You can access proxied method's arguments by injection of JoinPoint instance and invoking getArgs() method on it. Sample snippet below.
@Before("execution(* com.sample.SomeClass.doSometning(..))")
public void doSomethingBefore(JoinPoint joinPoint) {
   Object[] args = joinPoint.getArgs();
   for (Object arg: args) {
       // do whatever you like with the arguments
   }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论