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

Spring Aop(简单实现)

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

Spring Aop(简单实现)

代码结构

路径下的所有controller里面的方法,访问都需要经过aop
package com.example.demo.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DemoAop {

    @Around("execution(* com.example.demo.controller.*.*(..))")
    public Object tenantAop(ProceedingJoinPoint point) {
        long start = System.currentTimeMillis();
        Object proceed = null;
        //执行方法前
        try {
            //执行方法
            proceed = point.proceed();
            //执行方法
        } catch (Throwable throwable) {
            //抛出异常
            throwable.printStackTrace();
        }finally {
            //最终通知
        }
        long end = System.currentTimeMillis();
        System.out.println("aop打印执行时间:"+(end - start));
        return proceed;
    }
}

controller层代码

@RestController
public class TestController {

    @GetMapping("test")
    public void test(){
        System.out.println("执行方法内容");
    }
}

执行结果

 

扩展知识

前置通知 Before:执行方法前执行
后置通知 @AfterReturning:在方法不抛出异常的情况下执行
异常通知 @AfterThrowing:在连接点抛出异常后执行
最终通知 @After:执行方法后,不管有没有发生异常都会执行
环绕通知 @Around:方法执行前和执行后或者是异常,都会执行环绕通知内容

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

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

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