Spring Framework中的AOP编程之入门篇
2005-12-26 15:30 作者: Russell Miles 出处: bea 责任编辑:方舟
方面的重用 可以对方法跟踪方面进行扩展,提供一个稍微复杂的记录(Logging)方面。记录方面提供了一个很不错的重用例子,因为记录方面所需的许多特性都已经包含在方法跟踪方面中了。 在本例中,记录方面扩展了方法跟踪方面,以便显示附加的与(在应用程序的执行过程中)所引发的异常有关的信息。 要完全使用记录方面,需要对应用程序做一些更改。BusinessLogicException异常类提供了一个可以由IBusinessLogicInterface接口和BusinessLogic实现类新增的void bar()方法引发的异常。
public class BusinessLogicException extends Exception {}
public interface IBusinessLogic { public void foo();
public void bar() throws BusinessLogicException; }
public class BusinessLogic implements IBusinessLogic { public void foo() { System.out.println("Inside BusinessLogic.foo()"); }
public void bar() throws BusinessLogicException { System.out.println("Inside BusinessLogic.bar()"); throw new BusinessLogicException(); } } |
MainApplication类现在将对void bar()方法进行一次额外的调用,并处理选中的、可能由该方法引发的异常。
import org.springframeworkcontext.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext;
public class MainApplication { public static void main(String [] args) { // Read the configuration file ApplicationContext ctx = new FileSystemXmlApplicationContext( "springconfig.xml");
//Instantiate an object IBusinessLogic testObject = (IBusinessLogic) ctx.getBean("businesslogicbean");
//Execute the public methods of the bean testObject.foo();
try { testObject.bar(); } catch(BusinessLogicException ble) { System.out.println("Caught BusinessLogicException"); } } } |
来自方法跟踪方面的TracingBeforeAdvice和TracingAfterAdvice通知可以整体重用。LoggingThrowsAdvice类为新的异常记录提供了通知。
import org.springframework.aop.ThrowsAdvice; import java.lang.reflect.Method;
public class LoggingThrowsAdvice implements ThrowsAdvice { public void afterThrowing(Method method, Object[] args, Object target, Throwable subclass) { System.out.println("Logging that a " + subclass + "Exception was thrown."); } } |
应用记录方面的最后一步是修改springconfig.xml配置文件,使其包含新添加的LoggingThrowsAdvice通知。
![Click for larger view](http://image.360doc.com/DownloadImg/55657/1010720_1.gif) 图3显示了运行MainApplication并使用Spring框架应用了记录方面的UML顺序图。
|
图3. 记录方面应用到BusinessLogic bean之后的顺序图(单击图像查看大图) 此处的记录方面清楚地说明了如何重用现有方面以及如何在Spring框架中使用通知的throws形式。通过为before和after通知声明新的通知来重写现有的方法跟踪方面实现,可以实现更复杂的记录方面,记录到更复杂的记录框架,比如LOG4J。关于记录方面和例子应用程序的源代码,请参见本文末尾的参考资料小节。 结束语 本文展示了使用Spring框架中的基本AOP结构所应用的一些简单方面。在本系列的下一篇文章中,我们将介绍一些更实用的方面,探讨方面的生命周期,使用Spring框架的around通知,并使用Spring来应用AOP模式。
|