今天看了同事如何解决我好几天都搞不定了的一个事务问题,瞬间觉得自己还是low爆了,原理不清楚,出个问题确实很难搞定。
现在问题解决了,只能回想了。
项目有3个主要配置文件,分别是spring、springmvc、web。
我把代码贴进来吧。下面是web.xml文件内容
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>ws</display-name>
<!-- 配置请求过滤器,编码格式设为UTF-8,避免中文乱码 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 指定spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring/spring-context*.xml</param-value>
</context-param>
<!-- Spring ApplicationContext 载入,可以继承此接口进行扩展 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring 刷新Introspector防止内存泄露 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 使spring支持request、session及globalsession的作用域 -->
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- SpringMVC核心分发器 -->
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring/spring-mvc*.xml</param-value>
</init-param>
<!-- 取消其自动注册的异常解析器 -->
<init-param>
<param-name>detectAllHandlerExceptionResolvers</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!--===============================================shiro过虑器================================================-->
<!-- shiro过虑器,DelegatingFilterProxy通过代理模式将spring容器中的bean和filter关联起来 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<!-- 设置true由servlet容器控制filter的生命周期 -->
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
<!-- 设置spring容器filter的bean id,如果不设置则找与filter-name一致的bean-->
<init-param>
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- gzip filter
<filter>
<filter-name>GZIPFilter</filter-name>
<filter-class>com.ydkj.ws.common.filter.GZIPFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>GZIPFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
-->
<!-- etag filter -->
<!-- <filter> -->
<!-- <filter-name>etagFilter</filter-name> -->
<!-- <filter-class>com.ydkj.ws.common.filter.EtagHeaderFilter</filter-class> -->
<!-- <filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class> -->
<!-- </filter> -->
<!-- 错误页面 -->
<error-page>
<error-code>400</error-code>
<location>/WEB-INF/views/400.html</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/WEB-INF/views/403.html</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/views/404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/views/500.html</location>
</error-page>
</web-app>
,其次是spring-context.xml文件,
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<description>Spring Configuration</description>
<!-- 使用Annotation自动注册Bean,解决事务失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。 -->
<context:component-scan base-package="com.ydkj">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 加载配置属性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath*:properties/webview.properties" />
<context:property-placeholder ignore-unresolvable="true" location="classpath*:properties/base_config.properties" />
<context:property-placeholder ignore-unresolvable="true" location="classpath*:properties/redis.properties" />
<!-- 数据库连接、用户名、密码加密处理 -->
<bean id="propertyConfigurer" class="com.ydkj.ws.config.EncryptPropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:jdbc.properties</value>
</list>
</property>
<!-- 加密的属性字段集合 -->
<property name="encryptedProps">
<set>
<value>jdbc.url</value>
<value>jdbc.username</value>
<value>jdbc.password</value>
</set>
</property>
</bean>
<!-- 数据源配置, 使用 Druid 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
<property name="driverClassName" value="${jdbc.driver}" />
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${jdbc.pool.init}" />
<property name="minIdle" value="${jdbc.pool.minIdle}" />
<property name="maxActive" value="${jdbc.pool.maxActive}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="${jdbc.testSql}" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
</bean>
<bean id="myP6DataSource" class="com.p6spy.engine.spy.P6DataSource">
<constructor-arg>
<ref bean="dataSource"/>
</constructor-arg>
</bean>
<!-- Mybatis配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="myP6DataSource" />
<property name="typeAliasesPackage" value="com.ydkj" />
<property name="mapperLocations" value="classpath:/mappings/**/*.xml" />
<property name="configLocation" value="classpath:/mybatis-config.xml" />
</bean>
<!-- 扫描basePackage下所有以 @MyBatisDao注解的接口注解的接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<property name="basePackage" value="com.ydkj"/>
<property name="annotationClass" value="com.ydkj.common.persistence.annotation.MyBatisDao" />
</bean>
<!-- 配置SQLSession模板 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<!-- 声明式事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="select*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="query*" read-only="true" propagation="SUPPORTS"/>
<!-- 开启新事务 -->
<tx:method name="error*" propagation="REQUIRES_NEW"/>
<tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* *..*ServiceImpl.*(..))||execution(* com.ydkj.*.service.*.*(..))||execution(* com.ydkj.*.*.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
</aop:config>
<!-- <aop:aspectj-autoproxy proxy-target-class="true"/> -->
<!-- 使用annotation注解方式配置事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- spring data redis -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<property name="password" value="${redis.pass}" />
<property name="timeout" value="10000" />
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
<!-- 如果不配置Serializer,那么存储的时候智能使用String,如果用User类型存储,那么会提示错误User can't cast
to String!!! -->
<property name="keySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean
class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashValueSerializer">
<bean
class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
</bean>
<import resource="classpath*:spring-context-shiro.xml"/>
</beans>
再就是springmvc配置文件,spring-mvc.xml,
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 使用Annotation自动注册Bean,只扫描@Controller -->
<context:component-scan base-package="com.ydkj" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<mvc:interceptors>
<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->
<bean class="com.ydkj.ws.Interceptor.SpringMVCInterceptor"/>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的 -->
<bean class="com.ydkj.ws.Interceptor.SpringMVCInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<!--Spring3.1开始的注解 HandlerMapping -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<!--Spring3.1开始的注解 HandlerAdapter -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />
<!-- 视图解释类 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="${web.view.prefix}" />
<property name="suffix" value="${web.view.suffix}" />
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>
<!-- 定义无Controller的path<->view直接映射 -->
<mvc:view-controller path="/ws" view-name="redirect:${web.view.index}"/>
<!-- 对静态资源文件的访问, 将无法mapping到Controller的path交给default servlet handler处理 -->
<mvc:default-servlet-handler />
<!-- 配置swagger展示页面 -->
<bean class="springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration" id="swagger2Config"/>
<mvc:annotation-driven/><!-- 默认的注解映射的支持 -->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
<bean class="com.ydkj.ws.common.swagger.SpringfoxDocConfig"></bean>
</beans>
排除方法依次是检查mysql数据库表类型,确认为innodb,支持事务。
确认包扫描时顺序,spring不扫描controller,springmvc扫描controller,父子容器的关系,有一篇文章介绍。
http://blog.csdn.net/yeluosc/article/details/35650501
排除了这两个问题后,又定位web容器加载顺序,确认先加载spring,再加载springmvc。
到这里看不出问题了。
这个项目是参考一个SSH架构的项目做的,关于SSH架构的项目配置,参考我的另外一篇博文。
症结所在:com.p6spy.engine.spy.P6DataSource的使用不当导致。
hibernate有自己事务的实现
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
abstract="false" lazy-init="default" autowire="default">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
这个时候给事务注入sqlFactory,而sqlFactory定义的dataSource是myP6DataSource。
而mybatis没有sqlFactory,只有sqlSessionFactory,我的配置文件里sqlSessionFactory定义的dataSource是 myP6DataSource,正好配置的transactionManager没有使用myP6DataSource,而是直接配置的dataSource。如果改成下面的配置,则问题早就解决了。
<property name="dataSource" ref="myP6DataSource" />
唉,,,,学无止境啊