Spring宣告式事務的兩種配置方式(註解/xml)
阿新 • • 發佈:2020-09-12
application配置tx:annotation-driven
配置宣告式事務tx:TransactionManager
宣告式事務需要資料來源所以需要配置DataSource
使用:在類或者方法上新增@Transactional
基於xml式宣告式事務
配置切入點表示式aop:pointcut
關聯切入點表示式aop:advisor pointcut-ref ,advic
配置事務通知tx:advice,需要關聯事務管理器 DataSourceTransactionManager,需要關聯資料來源
配置資料來源DataSource
<!--1.元件掃描--> <context:component-scan base-package="com.ybbit"> <!--排除controller掃描--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--2.載入配置檔案--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--3.配置資料來源資訊--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--4.配置SQLSessionFactory工廠--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--指定mybatis全域性配置檔案--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!--指定資料來源--> <property name="dataSource" ref="dataSource"/> <!--指定mapper檔案的位置--> <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/> </bean> <!--5.配置AccountDao介面所在的包--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ybbit.dao"/> </bean> <!--配置可以執行批量的sqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/> <constructor-arg name="executorType" value="BATCH"/> </bean> <!--6.配置spring宣告式事務管理--> <!--事務管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--7.配置事務通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!--8.配置AOP增強--> <aop:config> <aop:pointcut id="pt1" expression="execution(* com.ybbit.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/> </aop:config>