Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 4 Join point to get method argument names and values

I am using Spring 4.3. Is it possible to get method parameter names and values passed to it? I believe this can be done using AOP (before advice) if possible could you please give me a source code.

like image 793
Debopam Avatar asked Jun 19 '17 16:06

Debopam


People also ask

What is a joinpoint in Spring AOP?

In Spring AOP, a join point always represents a method execution. Join point information is available in advice bodies by declaring a parameter of type org.aspectj.lang.JoinPoint. We’ll now learn about join points, and how we can use arguments in the advice methods to get information about join points.

Is it possible to get the method parameters of a joinpoint?

This is possible. See my answer on this page. In your AOP advice you can use methods of the JoinPoint to get access to methods and their parameters. There are multiple examples online and at stackoverflow.

How do I access the joinpoint argument in the advice?

To access the argument, we should provide a JoinPoint argument to the advice: This PCD limits matching to join points within types that have the given annotation: This PCD limits matching to join points where the subject of the join point has the given annotation. For example, we can create a @Loggable annotation:

How to get all available information about a method in spring?

In this article, we saw how to get all the available information about a method using a Spring AOP aspect. We did that by defining a pointcut, printing out the information into the console, and checking the results of running the tests. The source code for our application is available over on GitHub.


2 Answers

CodeSignature methodSignature = (CodedSignature) joinPoint.getSignature();
String[] sigParamNames = codeSignature.getParameterNames(); 

You can get method signature arguments names.

like image 60
sundar.sat84 Avatar answered Sep 19 '22 13:09

sundar.sat84


The following works as expected (Java 8 + Spring 5.0.4 + AspectJ 1.8.13):

@Aspect
@Component
public class SomeAspect {

    @Around("@annotation(SomeAnnotation)")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();

        System.out.println("First parameter's name: " + codeSignature.getParameterNames()[0]);
        System.out.println("First argument's value: " + joinPoint.getArgs()[0]);

        return joinPoint.proceed();
    }
}
like image 37
snorbi Avatar answered Sep 19 '22 13:09

snorbi