Spring AOP学习笔记

开发 后端
本文将详细介绍如何通过Spring.AOP特性实现异常的统一处理,以及其中中括号括起来的前三个参数是可选的,返回值可以是任意数据类型。

通常我们对于异常的处理方式都是大同小异的,要么直接捕获并处理,要么让它抛向上一层,要么就是记录到日志里,或者发邮件提供管理员,但这样下来一个项目中便会到处充斥着 try/catch ,并且 catch 中的代码基本类似,于是我们闻到的其中难闻的坏味道。

本文将介绍如何通过 Spring.AOP 特性实现异常的统一处理,如果我们需要在异常发生时做一些操作的话我们就必须实现 Spring.Aop.IThrowsAdvice,该接口没有任何实现方法,是一个空接口,它仅仅做为一个标记接口而存在,但实现了 IThrowsAdvice 接口的类必须定义至少一个 AfterThrowing 方法,方法的签名如下:AfterThrowing([MethodInfo method, Object[] args, Object target], Exception subclass);

其中中括号括起来的前三个参数是可选的,返回值可以是任意数据类型。 Spring.Aop.Framework.Adapter.ThrowsAdviceInterceptor 类实现对实现了 Spring.Aop.IThrowsAdvice 派生类中的方法依赖注入,其中的 ThrowsAdviceInterceptor() 方法检查 Spring.Aop.IThrowsAdvice 的派生类是否定义了至少一个异常处理方法,如果没有则抛出 ArgumentException 异常,MapAllExceptionHandlingMethods()方法则在定义好的重载方法中查找出异常类型与最后一个参数所定义的类型中最接近的方法,而且我们不应该在其中实现了两个相同异常类型的方法,即使他们的参数数目不同,否则也将抛出 ArgumentException 异常。

[下面引用自《Spring 技术手册》第4章 P94 页中的一段话]注意到当异常发生时, Throw Advice 的任务只是执行对应的方法,您并不能在 Throw Advice 中将异常处理掉,在 Throw Advice 执行完毕后,原告的异常仍将传播至应用程序之中, Throw Advice 并不介入应用程序的异常处理,异常处理仍旧是应用程序本身所要负责的,如果想要在 Throw Advice 处理时中止应用程序的处理流程,作法是抛出其它的异常。

接下来看个 Throws Advice 的实际例子,首先定义 IHello 接口:

  1. using System;  
  2.     namespace TestThrowAdvice  
  3.     {  
  4.         public interface IHello  
  5.         {  
  6.             void Hello(string name);  
  7.         }  
  8.     } 

接着定义一个 HelloSpeaker 类来实现 IHello 接口,并在 Hello() 方法中模拟程序发生错误时的异常抛出:

  1. using System;  
  2.     namespace TestThrowAdvice  
  3.     {  
  4.         public class HelloSpeaker : IHello  
  5.         {  
  6.             public void Hello(string name)  
  7.             {  
  8.                 Console.WriteLine("Hello, " + name);  
  9.                 //抱歉! 程序错误! 发生异常 XD  
  10.                 throw new Exception("发生异常");  
  11.             }  
  12.         }  
  13.     } 

如果您需要在应用程序抛出异常时,介入 Throw Advice 提供一些服务,例如记录一些异常信息,则可以实现 Spring.Aop.IThrowsAdvice 接口,在这个例子中我使用了 log4net 组件来实现日志的记录:

  1. using System;  
  2. using Spring.Aop;  
  3. using log4net;  
  4. using log4net.Core;  
  5. using System.Reflection;  
  6. [assembly: log4net.Config.XmlConfigurator(Watch = true)]  
  7. namespace TestThrowAdvice  
  8. {  
  9.    public class SomeThrowAdvice : IThrowsAdvice  
  10.   {  
  11.       private ILog logger;  
  12.       public SomeThrowAdvice()  
  13.       {  
  14.          logger = LogManager.GetLogger(this.GetType());  
  15.       }  
  16.       public void AfterThrowing(MethodInfo method, Object[] args, Object target, Exception exception)  
  17.       {  
  18.          // 记录异常  
  19.         logger.Info("记录异常", exception);  
  20.       }  
  21.    }  
  22.  } 

接着在配置文件(我这里使用了独立配置文件)中写下以下的定义,让 Throw Advice 在异常发生时提供记录服务:

  1. xml version="1.0" encoding="utf-8"?> 
  2.     <objects xmlns="http://www.Springframework.net" xmlns:xsi=                                      "http://www.w3.org/2001/XMLSchema-instance" 
  3.              xsi:schemaLocation="http://www.Springframework.net  
  4.              http://www.Springframework.net/xsd/Spring-objects.xsd"> 
  5.       <object id="SomeThrowAdvice" type="TestThrowAdvice.                              SomeThrowAdvice, TestThrowAdvice" /> 
  6.       <object id="HelloSpeaker" type="TestThrowAdvice.HelloSpeaker,                                                    TestThrowAdvice" /> 
  7.       <object id="HelloProxy" type="Spring.Aop.Framework.                                                 ProxyFactoryObject, Spring.Aop" > 
  8.         <property name="ProxyInterfaces"> 
  9.           <list> 
  10.             <value>TestThrowAdvice.IHello,TestThrowAdvicevalue> 
  11.           list> 
  12.         property> 
  13.         <property name="Target"> 
  14.           <ref object="HelloSpeaker" /> 
  15.         property> 
  16.         <property name="InterceptorNames"> 
  17.           <list> 
  18.             <value>SomeThrowAdvicevalue> 
  19.           list> 
  20.         property> 
  21.       object> 
  22.     objects> 

最后剩下我们的程序入口 Main() 函数了:

  1. using System;  
  2. using Spring.Context;  
  3. using Spring.Context.Support;  
  4.     namespace TestThrowAdvice  
  5.     {  
  6.         public class Program  
  7.         {  
  8.             static void Main(string[] args)  
  9.             {  
  10.                 log4net.Config.XmlConfigurator.Configure();  
  11.                 IApplicationContext context = new XmlApplicationContext(@"../../SpringNet.xml");  
  12.                 IHello helloProxy = (IHello)context.GetObject("HelloProxy");  
  13.                 try  
  14.                 {  
  15.                     helloProxy.Hello("Justin");  
  16.                 }  
  17.                 catch (Exception ex)  
  18.                 {  
  19.                     // 应用程序的异常处理  
  20.                     Console.WriteLine(ex.Message);  
  21.                 }  
  22.             }  
  23.         }  
  24.     } 

【编辑推荐】

  1. Spring控制反转(IoC)容器
  2. Spring is coming
  3. 在Spring中进行集成测试
  4. Spring中的TopLink ServerSession
  5. Spring声明式事务
责任编辑:佚名 来源: 中国IT实验室
相关推荐

2009-06-19 18:38:01

Spring

2009-06-19 13:28:30

Spring AOPSpring 2.0

2022-06-07 07:58:45

SpringSpring AOP

2022-02-17 13:39:09

AOP接口方式

2017-03-29 09:08:25

Spring笔记

2009-09-29 10:00:40

Spring AOP框

2022-06-08 08:04:28

Springservicerepository

2009-06-19 11:09:27

Spring AOP

2021-03-01 23:26:41

日志Spring BootAOP

2023-03-29 08:24:30

2022-02-08 17:07:54

Spring BooSpring Aop日志记录

2009-06-18 14:54:52

Spring AOP

2012-09-27 09:47:43

SpringJava面向对象

2019-11-29 16:21:22

Spring框架集成

2012-09-28 10:20:14

IBMdw

2021-05-06 07:58:57

Spring BeanIOCAOP

2022-02-16 13:46:40

Spring Aop代码注解

2012-08-22 10:18:03

PHP

2021-05-06 18:17:52

SpringAOP理解

2020-12-11 08:04:22

SpringAOPBean
点赞
收藏

51CTO技术栈公众号