注解@Aspect实现AOP功能
2024-10-20 08:52:54
springboot中pom引入jar
<!-- aop 切面 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
要想把一个类变成切面类,需要两步,
① 在类上使用 @Component 注解 把切面类加入到IOC容器中
② 在类上使用 @Aspect 注解 使之成为切面类
相关代码
@Aspect
@Component
public class AspectTest {
/**
* 前置通知:目标方法执行之前执行以下方法体的内容
* @param jp
*/
@Before("execution(* com.springboot.aop.controller.*.*(..))")
public void beforeMethod(JoinPoint jp){
String methodName = jp.getSignature().getName();
System.out.println("【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
} /**
* 返回通知:目标方法正常执行完毕时执行以下代码
* @param jp
* @param result
*/
@AfterReturning(value="execution(* com.springboot.aop.controller.*.*(..))",returning="result")
public void afterReturningMethod(JoinPoint jp, Object result){
String methodName = jp.getSignature().getName();
System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】");
} /**
* 后置通知:目标方法执行之后执行以下方法体的内容,不管是否发生异常。
* @param jp
*/
@After("execution(* com.springboot.aop.controller.*.*(..))")
public void afterMethod(JoinPoint jp){
System.out.println("【后置通知】this is a afterMethod advice...");
} /**
* 异常通知:目标方法发生异常的时候执行以下代码
*/
@AfterThrowing(value="execution(* com.springboot.aop.controller.*.*(..))",throwing="e")
public void afterThorwingMethod(JoinPoint jp, NullPointerException e){
String methodName = jp.getSignature().getName();
System.out.println("【异常通知】the method 【" + methodName + "】 occurs exception: " + e);
} /**
* 环绕通知:目标方法执行前后分别执行一些代码,发生异常的时候执行另外一些代码
* @return
*/
@Around(value="execution(* com.springboot.aop.controller.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint jp){
String methodName = jp.getSignature().getName();
Object result = null;
try {
System.out.println("【环绕通知中的--->前置通知】:the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
//执行目标方法
result = jp.proceed();
System.out.println("【环绕通知中的--->返回通知】:the method 【" + methodName + "】 ends with " + result);
} catch (Throwable e) {
System.out.println("【环绕通知中的--->异常通知】:the method 【" + methodName + "】 occurs exception " + e);
} System.out.println("【环绕通知中的--->后置通知】:-----------------end.----------------------");
return result;
}
}
作者:胖百二
来源:CSDN
原文:https://blog.csdn.net/wellxielong/article/details/80642726
版权声明:本文为博主原创文章,转载请附上博文链接!
最新文章
- React-Native需要css和布局-20160902
- CSS零基础学习笔记.
- 学习日志 - Openwrt安装python然后wallproxy
- MyBatis学习(二)
- [转]GridView排序——微软提供Sort
- 。。。JDBC里面的sql与hibernate里面的hql有关占位符";?";的总结。。。
- 【转载】mysql 四种隔离级别分析
- Microsoft Visual Studio Professional 2012 专业版 下载
- 修改EF的默认约定模型的方式
- Sql server中根据object的定义查找object
- ACdream 1135(MST-最小生成树边上2个值,维护第一个最小的前提下让还有一个最小)
- 深入解读Resnet
- tornado+jsonrpc
- Windows 独立启动方式安装 Archiva
- WKWebView 加载本地HTML随笔
- JAVA记录-Web系统AJAX异步传递路径写法
- linux的python版本升级
- cgi,fast-cgi,php-cgi,php-fpm转载详解
- 小米3移动版 分区 调整/合并教程(16GB/64GB)
- Thinkphp5笔记三:创建基类