AOP拦截controller方法注入参数 代替@RequestBody

kyaa111 3年前 ⋅ 1097 阅读

效果如下

1.jpg

1.1.png

2.png

加上@Pass放弃aop拦截注入,使用spring mvc的参数注入

3.png

4.png

5.png

核心方法

package com.github.aop;



import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.annotations.Pass;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;


/**
 * @author mqpearth
 */
@Aspect
@Component
public class ControllerAspect {

    @Autowired
    ServletRequest request;
    
    ObjectMapper objectMapper = new ObjectMapper();

    @Pointcut("execution(public * com.github.controller.*.*(..))")
    public void logAspect() {
    }

    @PostConstruct
    public void config() {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Around("logAspect()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method method = methodSignature.getMethod();
        if (method.getAnnotation(Pass.class) != null) {
            return pjp.proceed();
        } else {
            return pjp.proceed(handleRequestBody(method));
        }
    }

    private Object[] handleRequestBody(Method method) throws IOException {
        BufferedReader br = request.getReader();
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            builder.append(line);
        }
        Parameter[] parameters = method.getParameters();
        Object[] objects = new Object[parameters.length];
        try {
            for (int i = 0; i < objects.length; i++) {
                objects[i] = objectMapper.readValue(builder.toString(), parameters[i].getType());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objects;
    }

}

package com.github.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 方法上标记此注解,不使用aop拦截注入参数
 *
 * @author mqpearth
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Pass {

}