1、使用springmvc导致事务不起作用时,首先查看是否组件重复扫描问题导致
由于采用的是SpringMVC、 MyBatis,故统一采用了标注来声明Service、Controller。服务器启动时的加载配置文件的顺序为web.xml---root-context.xml(Spring的配置文件)---servlet-context.xml(SpringMVC的配置文件),由于root-context.xml配置文件中Controller会先进行扫描装配,但是此时service还没有进行事务增强处理,得到的将是原样的Service(没有经过事务加强处理,故而没有事务处理能力),所以我们必须在root-context.xml中不扫描controller,同样,在springmvc的配置文件中不扫描service
application.xml
<context:property-placeholder location="classpath:jdbc.properties"/> <context:component-scan base-package="cn.edu.nuc"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!--mybatis的sqlsessionFactory配置--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-config.xml" /> <property name="mapperLocations" value="classpath:cn/edu/nuc/mybatis/mapper/*.xml" /> </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="add*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/> <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/> <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/> <tx:method name="*" propagation="REQUIRED" read-only="true"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointCut" expression="execution(* cn.edu.nuc.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointCut" /> </aop:config>
spring-mvc.xml
<!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射--> <mvc:annotation-driven /> <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean --> <context:component-scan base-package="cn.edu.nuc"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan>
2、注意:查看mysql数据库引擎是否支持事务
3、查看依赖注入:
1)spring默认使用jdk的动态代理添加事务/依赖注入,所以在往pring ioc容器中注册bean时,需要再实现类上加@Service、@Repository等。
2)BaseDaoImpl、BaseDao 上不用使用注解。
3)在依赖注入的时候,要使用接口的方式,eg:
@Autowired
public DemoService demoServiceImpl;