学习Spring之九:AOP in Spring
Spring IoC和 Spring AOP组合,一起形成了Spring,这样一个有机整体,使得构建轻量级的J2EE架构成为可能,而且事实证明,非常有效。没有Spring IoC的Spring AOP是不完善的,没有Spring AOP的Spring IoC是不健壮的。 本文研究Spring框架中的面向方面编程(Aspect-Oriented Programming,AOP),进而通过例子解析如何运用Spring中的所有通知类型和切入点来实现更实用的方面和面向方面设计模式。
AOP概念:
Advice:如何将before通知、afterReturning通知和afterThrowing通知声明为bean。
Pointcut:如何声明静态切入点逻辑以将XML Spring Bean Configuration文件中的所有内容联系在一起。
Advisor:关联切入点定义与通知bean的方式。
Spring AOP是使用代理来完成的,Spring 两种方式:JDK动态代理,需要设定一组代理接口;CGLIB 代理,可代理接口和类。Spring提供了5种Advice类型:Interception Around、Before、After Returning、Throw和Introduction。它们分别在以下情况下被调用:在JointPoint前后、JointPoint前、 JointPoint后、JointPoint抛出异常时、JointPoint调用完毕后。
配置文件:
1 <beans> 2 <bean id="myAOPProxy" class="MethodTimeCostInterceptor"/>17 18 <bean id="myPotincutAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">19 <property name="advice">20 <ref local="MyInterceptor"/>21 </property>22 <property name="patterns">23 <list>24 <value>.*</value>25 <value>.*</value>26 </list>27 </property>28 </bean>29 </beans>
分析代码:
1、<bean id="myAOPProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">声明注入了代理实例myAOPProxy。
2、 proxyInterfaces声明将被代理接口ITest。
3、 target声明被代理目的类。
4、 interceptorNames设置拦截器为myPotincutAdvisor。
5、 patterns为拦截器设置配匹方式,即在所被配匹成功的方法被调用时执行拦截器内容。
该配置文件,指定要加载一个接口与ITest相匹配的bean。该bean随后被关联到Test实现类。看起来好像是费了很大力气只为了加载一个简单的bean并调用一个方法,但是这个配置文件只是使 Spring框架可以透明地对应用程序应用其组件的众多特性的一个体现。