【框架】[Spring]纯Java方式实现AOP拦截-详解ThrowsAdvice异常通知

简介: 转载请注明出处:http://blog.csdn.net/qq_26525215本文源自【大学之旅_谙忆的博客】这篇博客讲了AOP代理-通知的3种方式: 1、MethodBeforeAdvice-前置通知 2、AfterReturningAdvice-正常返回后通知 3、MethodInterceptor-环绕通知 【框架】[Spring]纯Java的方式实现AOP切面(拦截)技术 现在本篇博客再详细讲解一下ThrowsAdvice-异常通知。

转载请注明出处:http://blog.csdn.net/qq_26525215

本文源自大学之旅_谙忆的博客

这篇博客讲了AOP代理-通知的3种方式:
1、MethodBeforeAdvice-前置通知
2、AfterReturningAdvice-正常返回后通知
3、MethodInterceptor-环绕通知
【框架】[Spring]纯Java的方式实现AOP切面(拦截)技术

现在本篇博客再详细讲解一下ThrowsAdvice-异常通知。

顾明思议,就是被代理的原型对象出异常了,就会运行到实现此接口中的一个方法。
这个和AfterReturningAdvice互补哦。

被代理的类:

package cn.hncu.javaImpl;

public class Person {
    public void run(){
        System.out.println("我在run...");
    }

    public void run(int i){
        System.out.println("我在run"+i+"...");
        throw  new  IllegalArgumentException();  
    }

    public void say(){
        System.out.println("我在say...");
    }

}

实现ThrowsAdvice的方法:

package cn.hncu.javaImpl;

import org.springframework.aop.ThrowsAdvice;

public class ThrowException implements ThrowsAdvice{
    public  void  afterThrowing(Exception e)  throws  Throwable{  
        System.out.println("出异常了..."+e);
    }
}

运行的方法:

@Test
    public void demo3(){
        ProxyFactoryBean factory = new ProxyFactoryBean();
        factory.setTarget(new Person());//给代理工厂一个原型对象

        //切面 = 切点 + 通知
        //切点
        JdkRegexpMethodPointcut cut = new JdkRegexpMethodPointcut();
        cut.setPatterns(new String[]{".*run.*",".*say.*"});//可以配置多个正则表达式

        Advice throwsAdvice = new ThrowException();

        //切面 = 切点 + 通知
        Advisor throwsAdviceAdvisor = new DefaultPointcutAdvisor(cut, throwsAdvice);

        factory.addAdvisors(throwsAdviceAdvisor);

        Person p2 = (Person) factory.getObject();//从代理工厂中获取一个代理后的对象

        p2.run();
        p2.run(2222);
    }

运行结果:

有几个需要注意的地方:
1、就是原型对象的异常不能抓!一旦抓取就无法运行afterThrowing。
也就是只有出异常了,且没被抓,才会运行这个方法。
2、不能在运行的方法中直接new ThrowsAdvice然后实现afterThrowing方法,这样因为出异常,线程挂了,也会无法运行这个afterThrowing方法。
也就是不能在测试的方法中直接:

Advice throwsAdvice = new ThrowsAdvice() {
            public  void  afterThrowing(Exception e)  throws  Throwable{  
                System.out.println("出异常了..."+e);
            }
        };

这样也无法实现原型对象处异常拦截。

ThrowsAdvice源代码分析:

直接看ThrowsAdvice接口的源代码:

/*
 * Copyright 2002-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aop;

/**
 * Tag interface for throws advice.
 *
 * <p>There are not any methods on this interface, as methods are invoked by
 * reflection. Implementing classes must implement methods of the form:
 *
 * <pre class="code">void afterThrowing([Method, args, target], ThrowableSubclass);</pre>
 *
 * <p>Some examples of valid methods would be:
 *
 * <pre class="code">public void afterThrowing(Exception ex)</pre>
 * <pre class="code">public void afterThrowing(RemoteException)</pre>
 * <pre class="code">public void afterThrowing(Method method, Object[] args, Object target, Exception ex)</pre>
 * <pre class="code">public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)</pre>
 *
 * The first three arguments are optional, and only useful if we want further
 * information about the joinpoint, as in AspectJ <b>after-throwing</b> advice.
 *
 * <p><b>Note:</b> If a throws-advice method throws an exception itself, it will
 * override the original exception (i.e. change the exception thrown to the user).
 * The overriding exception will typically be a RuntimeException; this is compatible
 * with any method signature. However, if a throws-advice method throws a checked
 * exception, it will have to match the declared exceptions of the target method
 * and is hence to some degree coupled to specific target method signatures.
 * <b>Do not throw an undeclared checked exception that is incompatible with
 * the target method's signature!</b>
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see AfterReturningAdvice
 * @see MethodBeforeAdvice
 */
public interface ThrowsAdvice extends AfterAdvice {

}

你会发现里面并没有一个抽象方法!也行会有小伙伴迷茫,那为什么我们要实现那个方法啊。
没办法,因为我们是用Spring的框架,Spring内部用类反射来匹配了的,实现这个接口必须要实现这4个方法中的一个:

public void afterThrowing(Exception ex)
public void afterThrowing(RemoteException)
public void afterThrowing(Method method, Object[] args, Object target, Exception ex)
public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)

它的源代码有解释的,英文好一点就能看懂啦。

至于为什么不直接在这个接口中写这4个抽象类,可能怕代码太冗余吧。
毕竟,我们实现这个接口,我们用到的方法只会有一个,而如果都被声明成抽象方法了,那么,用户实现接口也必须实现这4个方法,显得冗余了。
所以估计Spring就干脆定义成标识接口了吧。

本文章由[谙忆]编写, 所有权利保留。

转载请注明出处:http://blog.csdn.net/qq_26525215

本文源自大学之旅_谙忆的博客

目录
相关文章
|
2月前
|
XML Java 开发者
Spring Boot中的AOP实现
Spring AOP(面向切面编程)允许开发者在不修改原有业务逻辑的情况下增强功能,基于代理模式拦截和增强方法调用。Spring Boot通过集成Spring AOP和AspectJ简化了AOP的使用,只需添加依赖并定义切面类。关键概念包括切面、通知和切点。切面类使用`@Aspect`和`@Component`注解标注,通知定义切面行为,切点定义应用位置。Spring Boot自动检测并创建代理对象,支持JDK动态代理和CGLIB代理。通过源码分析可深入了解其实现细节,优化应用功能。
115 6
|
16天前
|
Java 程序员 开发者
Java社招面试题:一个线程运行时发生异常会怎样?
大家好,我是小米。今天分享一个经典的 Java 面试题:线程运行时发生异常,程序会怎样处理?此问题考察 Java 线程和异常处理机制的理解。线程发生异常,默认会导致线程终止,但可以通过 try-catch 捕获并处理,避免影响其他线程。未捕获的异常可通过 Thread.UncaughtExceptionHandler 处理。线程池中的异常会被自动处理,不影响任务执行。希望这篇文章能帮助你深入理解 Java 线程异常处理机制,为面试做好准备。如果你觉得有帮助,欢迎收藏、转发!
75 14
|
1月前
|
XML Java 测试技术
Spring AOP—通知类型 和 切入点表达式 万字详解(通俗易懂)
Spring 第五节 AOP——切入点表达式 万字详解!
95 25
|
1月前
|
XML 安全 Java
Spring AOP—深入动态代理 万字详解(通俗易懂)
Spring 第四节 AOP——动态代理 万字详解!
78 24
|
19天前
|
缓存 Java 应用服务中间件
java语言后台管理若依框架-登录提示404-接口异常-系统接口404异常如何处理-登录验证码不显示prod-api/captchaImage 404 (Not Found) 如何处理-解决方案优雅草卓伊凡
java语言后台管理若依框架-登录提示404-接口异常-系统接口404异常如何处理-登录验证码不显示prod-api/captchaImage 404 (Not Found) 如何处理-解决方案优雅草卓伊凡
66 5
|
2月前
|
存储 安全 Java
Spring Boot 3 集成Spring AOP实现系统日志记录
本文介绍了如何在Spring Boot 3中集成Spring AOP实现系统日志记录功能。通过定义`SysLog`注解和配置相应的AOP切面,可以在方法执行前后自动记录日志信息,包括操作的开始时间、结束时间、请求参数、返回结果、异常信息等,并将这些信息保存到数据库中。此外,还使用了`ThreadLocal`变量来存储每个线程独立的日志数据,确保线程安全。文中还展示了项目实战中的部分代码片段,以及基于Spring Boot 3 + Vue 3构建的快速开发框架的简介与内置功能列表。此框架结合了当前主流技术栈,提供了用户管理、权限控制、接口文档自动生成等多项实用特性。
93 8
|
6月前
Micronaut AOP与代理机制:实现应用功能增强,无需侵入式编程的秘诀
AOP(面向切面编程)能够帮助我们在不修改现有代码的前提下,为应用程序添加新的功能或行为。Micronaut框架中的AOP模块通过动态代理机制实现了这一目标。AOP将横切关注点(如日志记录、事务管理等)从业务逻辑中分离出来,提高模块化程度。在Micronaut中,带有特定注解的类会在启动时生成代理对象,在运行时拦截方法调用并执行额外逻辑。例如,可以通过创建切面类并在目标类上添加注解来记录方法调用信息,从而在不侵入原有代码的情况下增强应用功能,提高代码的可维护性和可扩展性。
115 1
|
4月前
|
安全 Java 编译器
什么是AOP面向切面编程?怎么简单理解?
本文介绍了面向切面编程(AOP)的基本概念和原理,解释了如何通过分离横切关注点(如日志、事务管理等)来增强代码的模块化和可维护性。AOP的核心概念包括切面、连接点、切入点、通知和织入。文章还提供了一个使用Spring AOP的简单示例,展示了如何定义和应用切面。
577 1
什么是AOP面向切面编程?怎么简单理解?
|
4月前
|
XML Java 开发者
论面向方面的编程技术及其应用(AOP)
【11月更文挑战第2天】随着软件系统的规模和复杂度不断增加,传统的面向过程编程和面向对象编程(OOP)在应对横切关注点(如日志记录、事务管理、安全性检查等)时显得力不从心。面向方面的编程(Aspect-Oriented Programming,简称AOP)作为一种新的编程范式,通过将横切关注点与业务逻辑分离,提高了代码的可维护性、可重用性和可读性。本文首先概述了AOP的基本概念和技术原理,然后结合一个实际项目,详细阐述了在项目实践中使用AOP技术开发的具体步骤,最后分析了使用AOP的原因、开发过程中存在的问题及所使用的技术带来的实际应用效果。
97 5
|
6月前
Micronaut AOP与代理机制:实现应用功能增强,无需侵入式编程的秘诀
【9月更文挑战第9天】AOP(面向切面编程)通过分离横切关注点提高模块化程度,如日志记录、事务管理等。Micronaut AOP基于动态代理机制,在应用启动时为带有特定注解的类生成代理对象,实现在运行时拦截方法调用并执行额外逻辑。通过简单示例展示了如何在不修改 `CalculatorService` 类的情况下记录 `add` 方法的参数和结果,仅需添加 `@Loggable` 注解即可。这不仅提高了代码的可维护性和可扩展性,还降低了引入新错误的风险。
62 13

热门文章

最新文章