spring--事务配置的两种方式

###方式一:使用注解spring

<!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 使事务注解生效 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

备注:这种方式是,在须要加事务的方法上面使用@Transactional()来指定事务。
###方法二:使用xml配置数据库

####配置声明式事务流程
1.配置数据源
2.配置事务管理器,即该事务配置上面的数据源上
3.配置事务的属性(即传播特性),该属性添加到上述的事务管理器上
4.配置切面
4.1 定义切点,即事务添加到哪些类上
4.2 通知:链接事务属性和切点express

<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- 配置事务属性 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 定义查询方法只读 -->
			<tx:method name="query*" read-only="true"/>
			<tx:method name="find*" read-only="true"/>
			<tx:method name="get*" read-only="true"/>
			
			<!-- 主数据库操做 -->
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			
			<!-- 其它方法使用默认事务策略 -->
			<tx:method name="*"/>
			
		</tx:attributes>
	</tx:advice>

	<!-- 配置切面 -->
	<aop:config>
		<!-- 定义切面,全部的service的全部的方法 -->
		<aop:pointcut expression="execution(* com.test.spring.service.*.*(..))" id="txPointcut"/>
		<!-- 添加事务到切面上 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
	</aop:config>
相关文章
相关标签/搜索