简单自定义注解与使用

注解,写一个简单的注解,用于标记方法;标记的方法当aop的切点

/**
 * 自定义注解:日志记录
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAop {
}

方法应用

@RestController
@RequestMapping("/xxx")
public class XxxController {
    @Autowired
    private UserService userService;

    //注解标记
    @LogAop
    @GetMapping("/getOrder/{id}")
    public String getOrder(String id) {
        String data = userService.getInfo(a);
        return data;
    }
}

AOP方法

@Aspect
@Component
public class HttpLog {

    @Autowired
    private XxxxDao xxxxDao;

    /**
     * 1.设置切点
     */
    @Pointcut("@annotation(com.xxx.start.server.xxx.LogAop)")
    private void pointCut() {
    }

    @Around("pointCut()")
    public Object httpLog(ProceedingJoinPoint joinPoint) {

        long millisStart = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object proceed = "请求异常";
        //方法
        String method = request.getMethod();
        //对象
        String name = joinPoint.getTarget().getClass().getName();
        //参数
        Object[] args = joinPoint.getArgs();
        System.out.println(args.toString());
        StringBuffer stringBuffer = new StringBuffer();
        //参数拼接
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            if (i == args.length - 1 && arg != null) {
                stringBuffer.append(arg.toString());
            } else if (arg != null) {
                stringBuffer.append(arg.toString()).append(",");
            }
        }
        try {
            proceed = joinPoint.proceed();
            long end = System.currentTimeMillis();
            long resultTime = end - millisStart;
            //proceed 是返回数据,around 的专用,会有两次,当时间不同时,才是第二次
            if (resultTime != 0) {
                System.err.println("请求参数:" + stringBuffer);
                //查询sql
                List<xxx> data = xxxxDao.selectData();
                System.err.println("aop sql---->" + all);
            }
            return proceed;
        } catch (Throwable throwable) {
            System.out.println("err:" + throwable);
            return proceed + throwable.toString();
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值