spring aop实现原理转(全局异常,入参出参输出)

package com.example.demo.qin;


import com.alibaba.fastjson.JSONObject;
import com.example.demo.interfacecustom.custominterface;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class Aspecttest {
private static final Logger logger= LoggerFactory.getLogger(Aspecttest.class);
ThreadLocal<Long> startTime= new ThreadLocal<>();
@Pointcut("@annotation(com.example.demo.interfacecustom.custominterface)")
public void add() {
}

@After("add()")
public void after(JoinPoint joinPoint) {
ServletRequestAttributes ra =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ra.getRequest();
logger.info("<====================================================================");
logger.info("请求来源: => " + request.getRemoteAddr());
logger.info("请求URL: " + request.getRequestURL().toString());
logger.info("请求方式: " + request.getMethod());
logger.info("响应方法: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("请求参数 : " + Arrays.toString(joinPoint.getArgs()));
logger.info("---------------------------------------------------------------------");
startTime.set(System.currentTimeMillis());
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
//获取全类方法名
System.out.println(method);
custominterface annotation = method.getAnnotation(custominterface.class);
System.out.println(annotation.name());
}
@AfterReturning(pointcut = "add()",returning = "rst")
public void afterReturning(JoinPoint joinPoint,Object rst){
System.out.println("方法执行完执行.....afterReturning");
logger.info("耗时(毫秒) : " + (System.currentTimeMillis() - startTime.get()));
logger.info("返回数据: {}", JSONObject.toJSONString(rst));
logger.info("====================================================================>");
}
@AfterThrowing(pointcut = "add()",throwing = "a")
public String throwing(Throwable a){
System.out.println("看看是什么异常"+a);
Map<String,Object>map= new HashMap<>();
map.put("code",0);
map.put("msg","网络异常");
return JSONObject.toJSONString(map);
}

}

  通过requestcontextholder获取request ,获取相应的参数

controller

package com.example.demo.qin;

import com.example.demo.interfacecustom.AnontionTest;
import com.example.demo.interfacecustom.custominterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class qincotroller {
    @Autowired
    test2 test2;
    @RequestMapping("hell")
    @custominterface(name = "dd" )
    public String test1(@RequestParam(value = "name",defaultValue = "张三") String name,@RequestParam(value = "code",defaultValue = "em001") String code){
        AnontionTest te= new AnontionTest();
        test2.add();
        System.out.println(te.getName());
        String a=null;
        if(a.equals("a")) System.out.println(1234);
        return "helloword";
    }


}

 自定义注解

package com.example.demo.interfacecustom;


import java.lang.annotation.*;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface custominterface {
 String name() ;
}

 

后补 aop入参出参打印

package com.stylefeng.guns.rest.common.aop;

import com.stylefeng.guns.rest.common.util.CustomAnnotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @program: local_new1
 * @description: 输出入参出参
 * @author: Mr.qin
 * @create: 2018-12-24 09:33
 **/
@Component
@Aspect
public class CustomAnnotationAop {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    ThreadLocal<Long> starting= new ThreadLocal<>();
    @Pointcut("@annotation(com.stylefeng.guns.rest.common.util.CustomAnnotation)")
    public void param() {
    } ;
    @Before("param()")
    public void beforecustom(JoinPoint point) {
        Object result=null;
        String value=null;
        starting.set(System.currentTimeMillis());
        long start = System.currentTimeMillis();
        //获取方法参数
        Object[] args = point.getArgs();
        String requsetParam = Arrays.toString(args);
        //获取自定义注解的参数
        value = annotation(point);
        log.info(value+"入参"+requsetParam);
    }
     @AfterReturning(pointcut = "param()",returning = "result")
    public void afterCustom(JoinPoint joinpoint,Object result){
       String value = annotation(joinpoint);
        Long bgintime = starting.get();
        starting.remove();
        Long endtime=System.currentTimeMillis();
        log.info(value+"出参"+result.toString()+"总共执行时长" + (endtime - bgintime) + " 毫秒");
    }
    //抽取获取自定义注解的value值
    public String annotation(JoinPoint joinpoint){
        MethodSignature signature = (MethodSignature) joinpoint.getSignature();
        Method method = signature.getMethod();
        CustomAnnotation annotation = method.getAnnotation(CustomAnnotation.class);
        String value = annotation.value();
        return  value;
    }
}

 cotrolleradvice 全局异常

package com.stylefeng.guns.rest.common.aop;

import com.stylefeng.guns.rest.common.exception.CustomException;
import com.stylefeng.guns.rest.common.util.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program: local_new1
 * @description: 我的自定义拦截(全局异常拦截,(customexception)带有controller)
 * @author: Mr.qin
 * @create: 2018-12-21 17:54
 **/
@ControllerAdvice
public class CustomExceptionHadler  {

    private  Logger log = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler({CustomException.class})
    @ResponseBody
    public ResultData customException(CustomException ce){
        log.info("自定义业务异常"+ce);
        return new ResultData(0,ce.getMessage());
    }
    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResultData notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        return new ResultData(0,"系统异常");
    }
}

  

 https://blog.csdn.net/heirenheiren/article/details/36634497

https://blog.csdn.net/luanlouis/article/details/51095702

原文地址:https://www.cnblogs.com/qin-up/p/10130118.html