简体   繁体   English

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

[英]Spring AOP: exchanging information between methods

Suppose that I have a class called MyServlet , whose purpose is to respond to a user request:假设我有一个名为MyServlet的类,其目的是响应用户请求:

@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.所以如果我能在调用accept()之前透明地发生这种行为,我真的很喜欢它。 For this person, a Helper class can provide a logging functionality, which we will decorate with @Before :对于这个人,一个Helper类可以提供一个日志功能,我们将用@Before装饰@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.但是,能够获取提供给accept() (在本例中为Stringint )并将其传递给log()对我来说真的很有用,因为它可以让我准确记录用户和他们的 ID 进入我使用的任何日志存储。 How can I achieve this?我怎样才能做到这一点?

You can access proxied method's arguments by injection of JoinPoint instance and invoking getArgs() method on it.您可以通过注入JoinPoint实例并在其上调用getArgs()方法来访问代理方法的参数。 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
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM