Spring AOP:在方法之间交换信息

huangapple go评论76阅读模式
英文:

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
   }
}

huangapple
  • 本文由 发表于 2020年9月28日 01:38:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64091442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定