面向切面编程

1.必要pom
// 其余springboot 组件就不写了

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
     </dependency>

2.切面类编写

package com.association.common.all.util.log;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.weaver.Advice;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

// 定义切面注解 并 纳入springboot 管理进行自动配置
@Aspect
@Component
public class LogAspect {
    // 自己的日志类
    ILogger logger = new ILogger();

    //切面定义
    @Pointcut("(within(com.association..*)) && !(within(com.association.common.all.util.log.*))")
    public void advice() {
    }

    @Around("advice()")
    // 返回值即为对应的方法返回值 ,Object 代表 不改变返回值类型(反正多态可以强转回来)
    public Object cut(ProceedingJoinPoint pjp) throws Throwable {
        if (pjp.getTarget() instanceof ILogger || pjp.getTarget() instanceof Logger) {
            logger.info("aop error \n maybe cut the logger class ?");
        }
        Throwable trw = null;
        try {
            logger.info("method : {} starting...", pjp.getSignature().getName());
            logger.info("requestJson : {}", new ObjectMapper().writeValueAsString(pjp.getArgs()));
        } catch (Exception e) {
            //do nothing
            logger.error("maybe method is null ?");
        }
        try {
            return pjp.proceed(pjp.getArgs());
        } catch (Throwable throwable) {
            trw = throwable;
            logger.error("maybe run method error : \n{}", throwable.getMessage());
        }
        throw trw;
    }

    // Object 型的result 代表对返回值无要求
    // Object result 一定要是第二个参数 不然报错
    @AfterReturning(pointcut = "advice()", returning = "result")
    public void afr(JoinPoint jp, Object result) {
        logger.info("method : {} end...", jp.getSignature().getName());
        if (jp.getTarget() instanceof ILogger || jp.getTarget() instanceof Logger) {
            logger.info("aop error \n maybe cut the logger class ?");
        }
        try {
            logger.info("responseJson : {}", new ObjectMapper().writeValueAsString(result));
        } catch (JsonProcessingException e) {
            logger.error("parse result error : {}", e.getMessage());
        }
    }
}

相关文章
SpringBoot AOP代理学习及使用
AOP 切面表达式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值