栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot整合aop实现日志管理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot整合aop实现日志管理

依赖:


     org.springframework.boot
     spring-boot-starter-aop

自定义注解作为切入点

需要的属性根据自己业务需求进行自定义:

@Target(ElementType.METHOD)//表示注解在方法上生效
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogPrintConfig {

    //模块负责人
    String user() default "";

    //操作模块
    String module() default "";
}

配置切面类

@Aspect
@Component
public class LogRecordAop {

    
    @Pointcut("@annotation(com.kevin.aopdemo.annotation.LogPrintConfig)")
    public void logPointCut(){

    }


    //然后是大家熟悉的各个通知方法 环绕通知 前置通知 后置通知 异常通知 返回通知

    @Before("logPointCut()")
    public void before(JoinPoint joinPoint){
        // 获取目标类名
        String className = joinPoint.getTarget().getClass().getName();

        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        System.out.println(className+"类"+methodName+"方法被访问");
        // 获取参数
        Object[] args = joinPoint.getArgs();
        System.out.println("参数为:"+ Arrays.toString(args));

        // 获取当前执行的方法
        Method method = currentMethod(joinPoint, methodName);

        //获取注解内容
        LogPrintConfig erpLogConfig = method.getAnnotation(LogPrintConfig.class);

        // 获取模块名称、负责人
        String module = erpLogConfig.module();
        String user = erpLogConfig.user();

        System.out.println("这是前置通知");
        System.out.println(module+"模块");
        System.out.println(user+"为开发负责人");
        //参数获取到了,具体处理根据自己的实际业务需求
    }

    @AfterReturning(returning = "response", pointcut = "logPointCut()")
    public void doAfter(JoinPoint joinPoint, Object response) throws Exception {
        //response 就是响应的返回值
        System.out.println("(返回通知)返回值:"+response);
    }

    private Method currentMethod(JoinPoint joinPoint, String methodName) {
        
        Method[] methods = joinPoint.getTarget().getClass().getMethods();
        Method resultMethod = null;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                resultMethod = method;
                break;
            }
        }
        return resultMethod;
    }
}
controller:
@RestController
@RequestMapping("/aop")
public class TestAopController {

    @LogPrintConfig(user = "小明",module = "xx模块")
    @RequestMapping("/helloWorld")
    public String helloWorld(){
        return "Hello world!";
    }
}

demo结构

打印结果 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/955998.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号