即兴的灵感

思维是一种艺术; 艺术需要灵感。

博客好友

最新评论

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
="org.springframework.aop.framework.ProxyFactoryBean">
 3         <property name="proxyInterfaces">
 4             <value>ITest</value>
 5         </property>
 6         <property name="target">
 7             <ref local = "test"/>
 8         </property>
 9         <property name="interceptorNames">
10             <value>myPotincutAdvisor</value>
11         </property>
12     </bean>
13     
14     <bean id="test" class="Test"/>
15     
16     <bean id="MyInterceptor" 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声明被代理目的类。
4interceptorNames设置拦截器为myPotincutAdvisor
5、
patterns为拦截器设置配匹方式,即在所被配匹成功的方法被调用时执行拦截器内容。

    该配置文件,指定要加载一个接口与ITest相匹配的bean。该bean随后被关联到Test实现类。看起来好像是费了很大力气只为了加载一个简单的bean并调用一个方法,但是这个配置文件只是使 Spring框架可以透明地对应用程序应用其组件的众多特性的一个体现


 
凤凰涅槃/浴火重生/马不停蹄/只争朝夕
     隐姓埋名/低调华丽/简单生活/完美人生

posted on 2007-09-29 01:50 poetguo 阅读(1019) 评论(1)  编辑  收藏 所属分类: Spring

评论

# re: Spring笔记之九(AOP in Spring) 2007-09-29 02:44 gfsd

ee zhen e!  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: