使用Spring AOP 自动代理配置声明式事务

来源:互联网 发布:浪迹教育 知乎 编辑:程序博客网 时间:2024/05/17 02:52

我们可以使用下面两种方式消除proxyFactoryBean的繁重配置

1.继承parent bean

2.使用aop 自动代理

spring中的事务都是基于AOP的,我们同样可以使用自动代理消除TransactionProxyFactoryBean的重负实例

首先,我们要做任何自动通知一样,需要声明一个bean,成为DefaultAdvisorAutoProxyCreator

 

<bean id="org.springfranework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
</bean>

 DefaultAdvisorAutoProxyCreator将在应用上下文中遍历advisor,自动用它们来代理匹配advisor的pointcut的所有bean,对于事务,应该使用advisor是TransactionAttributeSourceAdvisor

 

<bean id="transactionAdvisor" class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
    
<constructor-arg>
      
<ref bean="transactionInterceptor"/>
    
</constructor-arg>
 
</bean>

 

TransactionAttributeSourceAdvisor是一个羽翼丰满的AOP Advisor,同样,他有一个pointcut和一个advisor构成,这个pointcut是静态方法pointcut,他根据事物属性来源确定一个方法是否和一些事务属性关联,关于拦截器advisor,通过一个构造参数transactionInterceptor

   

<bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         
<property name="dataSource">
             
<ref bean="dataSource"/>
         
</property>
</bean> 
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
  
<property name="transactionManager">
    
<ref bean="transactionManager"/> 
  
</property>
  
<property name="transactionAttributeSource">
    
<ref bean="transactionAttributeSource"/>
  
</property>
</bean>

 

为自动代理选择一个transactionAttributeSource

 

<bean id="transactionAttributeSource" class="org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource">
   
<property name="properties">
     
<props>
       
<prop key="get*">PROPAGATION_SUPPORTS</prop>
     
</props>
   
</property>
</bean>

 

关于属性源,我们有一个更好的解决方法

 


<bean id="transactionAttributeSource" class="org.springframework.transaction.interceptor.MethodMapTransactionAttributeSource">
   
<property name="methodMap">
     <map>
               <entry key="com.springaction.service.CourseServiceImpl.get*">
                     <value>PROPAGATION_SUPPORT</value>
                </entry>
         </map>
      </property>
</bean>

 

等等还没有完,我们更好的选择是使用AttributesTransactionAttributeSouce,即元数据,我们使用方法事务化和非事务化,只不过是添加合适的元数据到方法里而已

原创粉丝点击