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>

相關文章
相關標籤/搜索