Jason
Jason

Reputation: 2915

Spring AOP: exchanging information between methods

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?

Upvotes: 0

Views: 49

Answers (1)

Piotr Podraza
Piotr Podraza

Reputation: 2029

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

Upvotes: 1

Related Questions