Spring横切面(advice),增强(advisor),切入点(PointCut)的一点理解:
1.Spring管理事务有2种,其中一种是HibernateTransactionManager管理
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
这样当定义切面时可以注入会话工厂属性如下:
<!-- 配置事务处理的Bean,定义切面(advice) -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="query*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="save*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="del*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
2.对数据库的操作都属于事务的操作,而数据库默认是读已提交 read-only="true"形式
当读写操作时会调用DAO方法,而操作DAO的核心业务是Service,即 Spring,然而Spring
要对调用DAO的方法加以控制,所以就产生了切面(advice) //这个切面相当于一道防护门。
3.切面(advice)有了,Spring自己会找到应该执行哪些DAO里的方法了,(因为DAO已经注入到了Spring中;即service层引用Dao层)
所以自身的防护就变得复杂了,所以需要紧密耦合,自然增强就产生了 。如下:
<!-- 配置AOP -->
<aop:config>
<aop:pointcut id="daoMethod" expression="execution(public * com.dvp.module.*.*.*.dao.impl..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethod"/>
</aop:config>
<aop:config>
<aop:pointcut id="daoMethod2" expression="execution(public * com.dvp.base.dao.impl..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethod2"/>
</aop:config>
//OK所以一个Spring增强(advisor)=切面(advice)+切入点(PointCut)
在AOP中有几个概念:
— 方面(Aspect):一个关注点的模块化,这个关注点实现可能另外横切多个对象。事务管理是J2EE应用中一个很好的横切关注点例子。方面用Spring的Advisor或拦截器实现。
— 连接点(Joinpoint):程序执行过程中明确的点,如方法的调用或特定的异常被抛出。
— 通知(Advice):在特定的连接点,AOP框架执行的动作。各种类型的通知包括“around”、“before”和“throws”通知。
— 切入点(Pointcut):指定一个通知将被引发的一系列连接点的集合。AOP框架必须允许开发者指定切入点,例如,使用正则表达式。
所以<aop:aspect>实际上是定义横切逻辑,就是在连接点上做什么,<aop:advisor>则定义了在哪些连接点上应用什么<aop:aspect>。Spring这样做的好处就是可以让多个横切逻辑 (即<aop:aspect>定义的)多次使用,提供可重用性。
总的来说:
1、Adivisor是一种特殊的Aspect,Advisor代表spring中的Aspect
2、advisor只持有一个Pointcut和一个advice,而aspect可以多个pointcut和多个advice