1. 程式人生 > >Springboot @Valid 用AOP統一引數校驗以及日誌輸出

Springboot @Valid 用AOP統一引數校驗以及日誌輸出

程式碼如下

 package com.st.user.config;

import com.alibaba.fastjson.JSONObject;
import com.st.common.base.exception.helper.CompanyEnum;
import com.st.common.base.exception.helper.ExceptionInfo;
import com.st.common.base.exception.helper.ProjectEnum;
import com.st.common.base.utils.ResponseResultUtil;
import com.st.common.vo.ResponseResult;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.CodeSignature;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.util.*;

/**
 * @program: st-store-master
 * @description: 請求日誌AOP
 * @author: 陳家樂
 * @create: 2018-11-10 16:32
 **/

@Aspect
@Component
public class WebLogAspect {

    private Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    @Pointcut("execution(public * com.st.user.controller.*..*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void before(JoinPoint joinPoint){ // 獲取開始時間
        // 接收到請求,記錄請求內容
        //獲取方法
        MethodSignature joinPointObject = (MethodSignature) joinPoint.getSignature();
        Method method = joinPointObject.getMethod();

        //獲取swagger方法文件註解
        boolean flag = method.isAnnotationPresent(ApiOperation.class);
        if (flag) {
            ApiOperation annotation = method.getAnnotation(ApiOperation.class);
            logger.info("進入: {}方法," ,annotation.value());
        }
        logger.info("方法名{}" ,joinPointObject.getDeclaringTypeName() + "." + joinPointObject.getName());
    }

    @Around("webLog() &&args(..,bindingResult)")
    public Object doAround(ProceedingJoinPoint joinPoint,BindingResult bindingResult) throws Throwable {
        Long startTime = System.currentTimeMillis();
        Object retVal;
        if(bindingResult.hasErrors()){
            List<ObjectError> ls=bindingResult.getAllErrors();
            StringBuffer sb = new StringBuffer();
            for (ObjectError one : ls) {
                sb.append(one.getDefaultMessage());
            }
            retVal= ResponseResultUtil.bulidFailResponseResult(ExceptionInfo.PARAMETER_ERROR_INNER.code(CompanyEnum.ZYSTORE.code(), ProjectEnum.ST_STORE_PRODUCT.code()), sb.toString());
        }else {
            retVal = joinPoint.proceed(joinPoint.getArgs());
        }
        logger.info("返回內容 {}: " ,JSONObject.toJSONString(retVal));
        Long endtime = System.currentTimeMillis();
        logger.info("執行耗時為{}:" ,endtime-startTime + "ms");
        return retVal;

    }


}