在使用注解+AOP时,可以通过around等方法的参数获取到使用注解的方法、方法入参,以及request中的query等内容。

Annotation+@Aspect完整示例

//注解类
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DemoAnnotation {
    String value() default "";
}

//Aspect类
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
class DemoAspect {

    @Around(value = "@annotation(com.niannian.redis.annotation.DemoAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取类名
        Class clazz = joinPoint.getTarget().getClass();
        //获取方法名
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //获取参数名
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] argNames = u.getParameterNames(method);
        //获取参数值
        Object[] argValues = joinPoint.getArgs();

        //获取request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //request-query
        String queryStr = request.getQueryString();
        //request-请求方式
        String requestMethod = request.getMethod();
        //request-请求路径
        String requestURI = request.getRequestURI();

        return joinPoint.proceed();
    }

}

获取方法名及方法参数

//获取类名
Class clazz = joinPoint.getTarget().getClass();
//获取方法名
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
//获取参数名
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] argNames = u.getParameterNames(method);
//获取参数值
Object[] argValues = joinPoint.getArgs();

获取request

//获取request
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();