Spring 事务学习

先看项目的三个配置文件html

spring.xmljava

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
">

	<!-- 引入属性文件 
	<context:property-placeholder location="classpath:jdbc.properties" />
	-->
	<!-- 引入属性文件 自定义-->
	<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
            	<!-- 系统上虽然说能够配置多个properties文件,但要求只能有一个,并且统一命名为(config.properties),log4j.properties除外 -->
                <value>classpath*:config.properties</value>
             
                <!-- 可配置多个,到时均可以经过ProHolder.getConfigValue(key)这种方式获取其值
                <value>classpath*:mybatis/service.properties</value>
                 -->
            </list>
            
        </property>
        <property name="fileEncoding" value="UTF-8"></property>
    </bean>
    <bean id="propertyConfigurer" class="com.dashu.base.common.PropertiesConfig">
        <property name="properties" ref="configProperties" />
    </bean>
    
	<!-- 自动扫描(自动注入) --> 
	<context:component-scan base-package="com.dashu" />
	<!-- 用于持有ApplicationContext,可使用SpringContextHolder.getBean('xxxx')的静态方法获得spring bean对象 -->
	<bean id="SpringContextHolder" class="com.dashu.base.util.SpringContextHolder"/>
	<!-- properties工具类 -->
	<bean id="ProHolder" class="com.dashu.base.util.ProHolder"/>
	
	<task:scheduled-tasks>
        <task:scheduled ref="checkSellHouseTask" method="canelScore" cron="0 0 16 * * ?"/>
    </task:scheduled-tasks>
</beans>

spring-mybatis.xmlweb

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">

	<!-- 配置数据源 -->
	<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<!-- 初始化链接数量 -->
		<property name="initialSize" value="${druid.initialSize}" />
		<!-- 最大并发链接数 -->
		<property name="maxActive" value="${druid.maxActive}" />
		<!-- 配置获取链接等待超时的时间 -->
		<property name="maxWait" value="${druid.maxWait}" />
	</bean>

	<!-- myBatis文件 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 	<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"> -->
		<property name="dataSource" ref="dataSource" />
		<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
		<property name="mapperLocations" value="classpath:mybatis/**/*Mapper.xml" />
		<!-- mybatis配置,主要是拦截器,分页拦截器插件 -->
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
	</bean>

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.dashu" />
		<property name="markerInterface" value="com.dashu.base.repository.SqlMapper"/>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>

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

	<!-- 拦截器方式配置事物 -->
 	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="append*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="modify*" propagation="REQUIRED" />
			<tx:method name="edit*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="remove*" propagation="REQUIRED" />
			<tx:method name="repair" propagation="REQUIRED" />
			<tx:method name="delAndRepair" propagation="REQUIRED" />

			<tx:method name="get*" propagation="SUPPORTS" />
			<tx:method name="find*" propagation="SUPPORTS" />
			<tx:method name="load*" propagation="SUPPORTS" />
			<tx:method name="search*" propagation="SUPPORTS" />
			<tx:method name="datagrid*" propagation="SUPPORTS" />

			<tx:method name="*" propagation="SUPPORTS" />
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<aop:pointcut id="transactionPointcut"
			expression="execution(* com.dashu.**.service..*Impl.*(..))" />
		<aop:advisor pointcut-ref="transactionPointcut"
			advice-ref="transactionAdvice" />
	</aop:config>

	<bean id="druid-stat-interceptor"
		class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
	</bean>
	<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
		scope="prototype">
		<property name="patterns">
			<list>
				<value>com.dashu.base.service.*</value>
				<value>com.dashu.mobile.core.service.*</value>
				<value>com.dashu.core.control.LoginRegisterController</value>
			</list>
		</property>
	</bean>
	<aop:config>
		<aop:advisor advice-ref="druid-stat-interceptor"
			pointcut-ref="druid-stat-pointcut" />
	</aop:config> -->

	
</beans>

spring-mvc.xmlspring

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="  
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
        http://www.springframework.org/schema/websocket 
        http://www.springframework.org/schema/websocket/spring-websocket.xsd
        http://www.springframework.org/schema/context  
		http://www.springframework.org/schema/context/spring-context-3.1.xsd  
		http://www.springframework.org/schema/mvc  
		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		">
	<!-- 
 	<bean id="customObjectMapper" class="com.dashu.base.common.DateFormatObjectMapper"></bean>
	 -->
	<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">
		<mvc:message-converters register-defaults="true">
			<!-- 将StringHttpMessageConverter的默认编码设为UTF-8 -->
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<constructor-arg value="UTF-8" />
			</bean>

			<!-- 时间格式化 处理 
			<bean
				class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
				<property name="objectMapper" ref="customObjectMapper"></property>
			</bean>
			-->
			
			<bean
				class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
			<!-- 将Jackson2HttpMessageConverter的默认格式化输出设为true -->
			<!-- 处理responseBody 里面日期类型 --> 
			<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="objectMapper">
	                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
	                    <property name="dateFormat">
	                        <bean class="java.text.SimpleDateFormat">
	                            <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"/>
	                        </bean>
	                    </property>
	                </bean>
	            </property>
	            <property name="prettyPrint" value="true" />
			</bean>
			<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
		</mvc:message-converters>
	</mvc:annotation-driven>
	<!-- REST中根据URL后缀自动断定Content-Type及相应的View -->
	<bean id="contentNegotiationManager"
		class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
		<!-- 设置为true 以忽略对header accept的支持 -->
		<property name="ignoreAcceptHeader" value="true" />
		<!-- 当url不加后缀区分时,默认显示的数据格式为json -->
		<property name="defaultContentType" value="application/json" />
		<property name="mediaTypes">
			<value>
				json=application/json
				xml=application/xml
			</value>
		</property>
	</bean>

	<!-- 引入属性文件 <context:property-placeholder location="classpath:jdbc.properties" 
		/> -->
	<!-- controller包(自动注入) -->
	<context:component-scan base-package="com.dashu">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository" />
	</context:component-scan>
	<!--静态资源访问 -->
	<mvc:default-servlet-handler />

	<mvc:resources mapping="/js/**" location="/js/" cache-period="31556926" />

	<!-- 定义跳转的文件的先后缀 ,视图模式配置 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 这里的配置个人理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
		<property name="prefix" value="/" />
		<property name="suffix" value=".html" />
	</bean>
	
	<!-- 配置文件上传,若是没有使用文件上传能够不用配置,固然若是不配,那么配置文件中也没必要引入上传组件包  
	<bean id="multipartResolver"
	class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="defaultEncoding" value="utf-8" />
	<property name="maxUploadSize" value="10485760000" />
	<property name="maxInMemorySize" value="40960" />
     </bean>
	-->
     
	
	<mvc:interceptors>
        <mvc:interceptor>
        <!-- 	<mvc:mapping path="/**"/> -->
        	<!-- <mvc:mapping path="/login/**"/> -->
            <mvc:mapping path="/suggestion/**"/>
            <mvc:mapping path="/core/**"/>
            <mvc:mapping path="/page/**"/>
            <bean id="mobileCommonInterceptor" class="com.dashu.common.intercepter.MobileCommonIntercepter"/>
        </mvc:interceptor>
    </mvc:interceptors>
    
    <!-- 若是如下配置报错,请在本xml文件的头<beans>引入相关的规则属性 , 以下
    xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
		……
    	http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		"
    -->
    
    <!-- 引用spring-mybatis.xml文件事务管理器 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	<!-- 对符合指定方法名称规则的方法进行事务声明配置 -->
	<tx:advice id="transactionAdviceMVC" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="append*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="modify*" propagation="REQUIRED" />
			<tx:method name="edit*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="remove*" propagation="REQUIRED" />
			<tx:method name="repair" propagation="REQUIRED" />
			<tx:method name="delAndRepair" propagation="REQUIRED" />

			<tx:method name="get*" propagation="SUPPORTS" />
			<tx:method name="find*" propagation="SUPPORTS" />
			<tx:method name="load*" propagation="SUPPORTS" />
			<tx:method name="search*" propagation="SUPPORTS" />
			<tx:method name="datagrid*" propagation="SUPPORTS" />

			<!-- <tx:method name="*" propagation="SUPPORTS" /> -->
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<!-- advice-ref="transactionAdviceMVC" 若是不想在本文件中写拦截方法的规则,能够直接引用spring-mybatis.xml文件中的transactionAdvice 
			execution 能够多个,配置 || && or and ……使用
		-->
		<aop:advisor advice-ref="transactionAdviceMVC" pointcut="execution(* com.dashu.mobile.sell.web.*Controller.*(..))  || execution(* com.dashu.core.control.*Controller.*(..))"/> 
	</aop:config>
</beans>

普通的事务直接直接在spring-mybatis.xml中配置声明式事务便可,或在service/dao层直接用注解事务@Transactional,本文主要说在controller层添加事务。sql

在controller层添加事务主要看spring-mvc.xml配置文件中的<tx:******>和<aop:******>的配置,其中express

<tx:annotation-driven>必须,<tx:advice>、<aop:config>为声明式事务配置json

代码controller类中符合声明式事务的方法出错将进行事务回滚,不符合的不回滚spring-mvc

controller类中,不符合声明式事务的方法,也能够直接用注解式的事务,这样两种事务配合使用websocket

为何按spring 配置事务的通常做法没法配置在controller没起效果呢?如下是摘取网上别人(http://uule.iteye.com/blog/1852012)的总结mybatis

其实就是一个加载顺序的问题
首先使用了spring MVC的项目是不须要配置action bean  而是经过spring mvc的配置文件进行扫描注解加载的
spring事务配置文件还有上下文都是经过org.springframework.web.context.ContextLoaderListener加载的,
而spring MVC的action是经过org.springframework.web.servlet.DispatcherServlet加载的 这样就有个优先级的问题了  web是先启动ContextLoaderListener后启动DispatcherServlet 在ContextLoaderListener加载的时候action并没在容器中,因此如今使用AOP添加事务或者扫描注解都是无用的。 那么解决办法就是在DispatcherServlet 加载spring-MVC配置文件后再进行一次AOP事务扫描和注解事务扫描就OK了 <tx:annotation-driven transaction-manager="transactionManager"/> <aop:config>          <aop:advisor advice-ref="transactionAdvice" pointcut="execution(* com.yang.web.*.action.*.*(..))"/>  </aop:config>

相关文章
相关标签/搜索