温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring中@Transactional如何配置

发布时间:2021-12-20 10:54:49 来源:亿速云 阅读:350 作者:小新 栏目:互联网科技

这篇文章将为大家详细讲解有关Spring中@Transactional如何配置,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

  • 背景:

    1. spring老版本是使用TransactionProxyFactoryBean来实现对spring的事务进行配置(缺点自己google,一大堆的缺点)

    2. spring2.x引入了AOP(面向切面的编程)

    3. 当初项目也是喜欢用spring xml方式的配置,后来项目使用spring3.x版本,看到了@Transactional注解,个人觉得挺方便和实用。(具体什么原因,说不清)

  • 上代码

    1. <?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:aop="http://www.springframework.org/schema/aop"
             xmlns:tx="http://www.springframework.org/schema/tx"
      	   xsi:schemaLocation="
      		     http://www.springframework.org/schema/beans 
      		     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      		     http://www.springframework.org/schema/context
      		     http://www.springframework.org/schema/context/spring-context-3.2.xsd
      		     http://www.springframework.org/schema/tx
      		     http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
      		     http://www.springframework.org/schema/aop 
      		     http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
      
      
          <!-- ################# start ################ -->
      
          <context:component-scan base-package="com.xun.spring3.src"></context:component-scan>
      
          <bean id="placeholderConfig"
                class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
              <property name="location">
                  <value>classpath:/db.properties</value>
              </property>
          </bean>
      
          <!-- ################### end ############## -->
      
      	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
      		<property name="dataSource" ref="dataSource"></property>
      		<property name="configLocation">
      			<value>classpath:/sqlmap-config.xml</value>
      		</property>
      		<property name="mappingLocations">
      			<value>classpath*:/sqlmap/*.xml</value>
      		</property>
      	</bean>
      
          <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
                init-method="init" destroy-method="close">
              <property name="url" value="${jdbc.url}" />
              <property name="username" value="${jdbc.user}"></property>
              <property name="password" value="${jdbc.password}" />
      
              <property name="filters"><value>stat</value></property>
      
              <property name="maxActive"><value>20</value></property>
              <property name="initialSize"><value>1</value></property>
              <property name="maxWait"><value>60000</value></property>
              <property name="minIdle"><value>1</value></property>
      
              <property name="timeBetweenEvictionRunsMillis"><value>60000</value></property>
              <property name="minEvictableIdleTimeMillis"><value>300000</value></property>
      
              <property name="validationQuery"><value>SELECT 'x'</value></property>
              <property name="testWhileIdle"><value>true</value></property>
              <property name="testOnBorrow"><value>false</value></property>
              <property name="testOnReturn"><value>false</value></property>
      
              <property name="poolPreparedStatements"><value>true</value></property>
              <property name="maxOpenPreparedStatements"><value>20</value></property>
          </bean>
      
          <!--
              其实 不涉及到分布式事务的话,无需定义这个模板 sqlMapClient,因为basedao已经SqlMapClientDaoSupport这个类,
              SqlMapClientDaoSupport中已经有SqlMapClientTemplate这个属性了。
          -->
          <!--
          <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">
              <property name="sqlMapClient" ref="sqlMapClient"></property>
          </bean>
          -->
      
      	<!-- transaction confige -->
          <!--
              作用:开启对@Transactional注解的加工处理,以织入事务管理切面
              <tx:annotation-driven>属性说明:
              (1):属性transaction-manager:指定事务管理器名字,默认为transactionManager,当使用其他名字时需要明确指定
              (2):proxy-target-class: 如果为true,Spring将通过创建子类来代理业务类;
                                      如果为false(默认),则使用基于接口来代理。
                                      (ps:如果使用子类代理,需要在类路径中添加CGLib.jar类库)
              (3):order:如果业务类除事务切面外,还需要织入其它的切面(或者多个事务切面),通过该属性来控制切面在目标连接点的织入顺序
          -->
      	<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" />
      
          <!--proxy-target-class:默认false表示使用JDK代理,如果为true将使用CGLIB代理-->
          <!-- 使用CGLIB的话需要加上aspectjrt和aspectjweaver 的jar-->
          <aop:aspectj-autoproxy proxy-target-class="true" />
      
          <!-- 对于cobar对数据源的时候我们用这个 -->
          <!--<bean id="txManager" class="com.alibaba.cobar.client.transaction.MultipleDataSourcesTransactionManager">
      		<property name="cobarDataSourceService" ref="dataSources" />
          </bean>-->
          <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
              <property name="dataSource" ref="dataSource"></property>
          </bean>
      
      </beans>
    2. package com.xun.spring3.src.dao;
      
      import com.ibatis.sqlmap.client.SqlMapClient;
      import org.apache.commons.lang.StringUtils;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
      
      import javax.annotation.PostConstruct;
      import java.lang.reflect.ParameterizedType;
      import java.lang.reflect.Type;
      
      /**
       * 要求每个dao的命名以 Dao结尾
       * 泛型 ENTITY - 具体哪个实体
       * 泛型 PRIMARYKEY - 具体主键的类型
       * @Date : 2014/9/7 0007 20:41
       * @From : spring3-test
       * @Author : hebad90@163.com
       */
      public class BaseDao<ENTITY, PRIMARYKEY> extends SqlMapClientDaoSupport {
      
          @Autowired
          private SqlMapClient sqlMapClient;
      
          @PostConstruct
          private void initSuper() {
              /**
               * 初始化父类
               */
              super.setSqlMapClient( sqlMapClient );
          }
      
          private Class entityClass ;
      
          private String ibatisNamespace;
      
          protected BaseDao() {
              Type genType = getClass().getGenericSuperclass();
              Type[] params = ((ParameterizedType)genType).getActualTypeArguments();
              entityClass = (Class)params[0];
      
              /**
               * 获取当前 ibatis的命名空间 XxxDao 即命名空间为 xxx
               */
              this.ibatisNamespace = getIbatisNamespace( getClass() );
      
              System.out.println( "初始化当前环境成功,ibatisNamespace=["+this.ibatisNamespace+"],entityClass=[" + entityClass + "]" );
      
          }
      
          public PRIMARYKEY insert( ENTITY entity ) {
              return(PRIMARYKEY)super.getSqlMapClientTemplate().insert( this.ibatisNamespace + ".insert", entity );
          }
      
          public int update( ENTITY entity ) {
              return super.getSqlMapClientTemplate().update( this.ibatisNamespace + ".update", entity );
          }
      
          public ENTITY queryById( PRIMARYKEY primarykey ) {
              return ( ENTITY ) super.getSqlMapClientTemplate().queryForObject( this.ibatisNamespace + ".queryById", primarykey);
          }
      
          public int delete( ENTITY entity ) {
              return super.getSqlMapClientTemplate().delete( this.ibatisNamespace + ".delete", entity);
          }
      
      
          ///##############################
          private String getIbatisNamespace( Class clazz ) {
              String simpleName = clazz.getSimpleName();
              int index = StringUtils.indexOf( simpleName, "Dao" );
      
              return StringUtils.lowerCase( StringUtils.substring( simpleName, 0, index ) );
          }
      
      }
    3. @Transactional在何处使用?Spring建议我们在业务实现类上使用该注解,因为java的实现不能继承注解。所以,最好是在业务实现类上注解,这样不管<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" />中的proxy-target-class为true或者false,业务类都会启用事务机制。

    4. @Transactional的参数怎么使用?Spring中@Transactional如何配置




关于“Spring中@Transactional如何配置”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI