Java – how to access method properties using spring AOP (AspectJ style)?
•
Java
I need to accept some methods and their properties by using annotations as pointcuts, but how do I access them I have the following code that can successfully run the code before the method runs, but I don't know how to access these attrbiutes
package my.package;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.pointcut;
@Aspect
public class MyAspect {
@pointcut(value="execution(public * *(..))")
public void anyPublicMethod() {
}
@Around("anyPublicMethod() && @annotation(myAnnotation )")
public Object myAspect(ProceedingJoinPoint pjp,MyAnnotation myAnnotation)
throws Throwable {
// how can I access method attributes here ?
System.out.println("hello aspect!");
return pjp.proceed();
}
}
Solution
You can get them from the proceedingjoinpoint object:
@Around("anyPublicMethod() && @annotation(myAnnotation )")
public Object myAspect(final ProceedingJoinPoint pjp,final MyAnnotation myAnnotation) throws Throwable{
// retrieve the methods parameter types (static):
final Signature signature = pjp.getStaticPart().getSignature();
if(signature instanceof MethodSignature){
final MethodSignature ms = (MethodSignature) signature;
final Class<?>[] parameterTypes = ms.getParameterTypes();
for(final Class<?> pt : parameterTypes){
System.out.println("Parameter type:" + pt);
}
}
// retrieve the runtime method arguments (dynamic)
for(final Object argument : pjp.getArgs()){
System.out.println("Parameter value:" + argument);
}
return pjp.proceed();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
