0

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?

Jason
  • 2,495
  • 4
  • 26
  • 37
  • **(1)** `@EnableAspectJAutoProxy` should be on a separate `@Configuration` class, not on a `@Component`. **(2)** Your aspect intercepts `show()`, but your sample method is named `accept(String, int)`. So I am confused about what you want to achieve. The code does not speak for itself. So please update the question, then notify us by commenting here. – kriegaex Sep 28 '20 at 00:15

1 Answers1

1

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
   }
}
Piotr Podraza
  • 1,941
  • 1
  • 15
  • 26