热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Spring——XML配置事务、注解+XML、纯注解的配置方式

目录一、基于xml配置声明式事务1、解决银行转账问题2、事务方法tx:method属性配置3、CRUD通用事务配置二、基于注解配置声明式事务三、基于纯注解(JavaConfig)

目录


  • 一、基于 xml 配置声明式事务
    • 1、解决银行转账问题
    • 2、事务方法 tx:method 属性配置
    • 3、CRUD通用事务配置
  • 二、基于 注解 配置声明式事务
  • 三、基于 纯注解(JavaConfig) 配置声明式事务
  • 四、选择开发方式

在这里插入图片描述

Spring系列

  1. Spring — Spring简介、入门、配置 , IoC和DI思想
  2. Spring — IoC核心(基于XML)、DI核心(基于XML)
  3. Spring — 使用IoC和DI模拟注册案例、注解配置IoC和DI
  4. Spring — 静态代理、动态代理、拦截器思想
  5. Spring — AOP思想、AOP开发、Pointcut语法、注解配置AOP
  6. Spring — DAO层、Spring JDBC、Spring事务控制
  7. Spring — XML配置事务、注解+XML、纯注解的配置方式
  8. Spring整合MyBatis
  9. Spring Java Config — 组件注册相关注解
  10. Spring Java Config — 常用注解




一、基于 xml 配置声明式事务

跳转到目录

1、解决银行转账问题

跳转到目录
在上面引出事务的代码基础上,只需要修改xml配置文件


<beans xmlns&#61;"http://www.springframework.org/schema/beans"xmlns:xsi&#61;"http://www.w3.org/2001/XMLSchema-instance"xmlns:context&#61;"http://www.springframework.org/schema/context"xmlns:tx&#61;"http://www.springframework.org/schema/tx" xmlns:aop&#61;"http://www.springframework.org/schema/aop"xsi:schemaLocation&#61;"http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/txhttps://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"><context:property-placeholder location&#61;"classpath:db.properties"/><bean id&#61;"dataSource" class&#61;"com.alibaba.druid.pool.DruidDataSource"init-method&#61;"init" destroy-method&#61;"close"><property name&#61;"driverClassName" value&#61;"${jdbc.driverClassName}"/><property name&#61;"url" value&#61;"${jdbc.url}"/><property name&#61;"username" value&#61;"${jdbc.username}"/><property name&#61;"password" value&#61;"${jdbc.password}"/><property name&#61;"initialSize" value&#61;"${jdbc.initialSize}"/>bean><bean id &#61; "accountDao" class&#61;"com.sunny.dao.impl.AccountDaoImpl"><property name&#61;"dataSource" ref&#61;"dataSource"/>bean><bean id&#61;"accountService" class&#61;"com.sunny.service.impl.AccountServiceImpl"><property name&#61;"dao" ref&#61;"accountDao"/>bean><bean id&#61;"txManager" class&#61;"org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name&#61;"dataSource" ref&#61;"dataSource"/>bean><tx:advice id&#61;"txAdvice" transaction-manager&#61;"txManager"><tx:attributes><tx:method name&#61;"trans"/>tx:attributes>tx:advice><aop:config><aop:pointcut id&#61;"txPointcut" expression&#61;"execution(* com.sunny.service.*Service.*(..))"/><aop:advisor advice-ref&#61;"txAdvice" pointcut-ref&#61;"txPointcut"/>aop:config>
beans>

测试
在这里插入图片描述
在这里插入图片描述
成功!

2、事务方法 tx:method 属性配置

跳转到目录
元素的属性

  • 事务配置通知标签(增强)
    • 属性id&#xff1a;自定义唯一表示
    • transaction-manager属性&#xff1a;事务管理类&#xff0c;配置事务管理类的id属性值
  • 事务属性配置子标签
    • 事务方法标签
      • 属性name&#xff1a;方法名
      • 属性read-only&#xff1a;是否只读事务&#xff0c;查询都是只读&#xff0c;其他是非只读
      • 属性propagation&#xff1a;事务的传播行为&#xff0c;默认配置REQUIRED或者SUPPORTS
      • 属性isolation&#xff1a;事务隔离级别&#xff0c;默认配置DEFAULT
      • 属性timeout&#xff1a;事务超时时间&#xff0c;配置-1
      • 属性no-rollback-for&#xff1a;遇到什么异常不回滚&#xff0c;配置异常类名&#xff0c;多个类逗号分开
      • 属性rollback-for&#xff1a;遇到什么异常回滚
        • 以上回滚属性不配置&#xff0c;遇到异常就回滚
  • aop切面配置标签
    • 子标签
      • 属性advice-ref&#xff1a;引用通知&#xff0c;配置tx:advice标签的属性值
      • 属性pointcut&#xff1a;切点配置

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3、CRUD通用事务配置

跳转到目录

<tx:advice id&#61;"crudAdvice" transaction-manager&#61;"txManager"><tx:attributes><tx:method name&#61;"get*" read-only&#61;"true" propagation&#61;"REQUIRED"/><tx:method name&#61;"list*" read-only&#61;"true" propagation&#61;"REQUIRED"/><tx:method name&#61;"query*" read-only&#61;"true" propagation&#61;"REQUIRED"/><tx:method name&#61;"*" propagation&#61;"REQUIRED"/>tx:attributes>tx:advice>

二、基于 注解 配置声明式事务

跳转到目录
基于注解配置事务&#xff1a;在Service中&#xff0c;使用 &#64;Transactional注解

&#64;Transactional 注解的属性
在这里插入图片描述

  • &#64;Transactional 可以作用于接口、接口方法、类以及类方法上。当作用于类上时&#xff0c;该类中的所有 public方法将都具有该类型的事务属性&#xff0c;同时&#xff0c;我们也可以在方法级别使用该标注来覆盖类级别的定义(比如在查询方法上单独设置&#64;Transactional(readOnly&#61;true)。
    在这里插入图片描述
  • &#64;Transactional 注解可以作用于接口、接口方法、类以及类方法上&#xff0c;但是 Spring 建议不要在接口或者接口方法上使用该注解&#xff0c;因为这只有在使用基于接口的代理时它才会生效。另外&#xff0c; &#64;Transactional 注解应该只被应用到 public 方法上&#xff0c;这是由 Spring AOP 的本质决定的。如果你在 protected、private 或者默认可见性的方法上使用 &#64;Transactional 注解&#xff0c;这将被忽略&#xff0c;也不会抛出任何异常。

Java代码

&#64;Repository
public class AccountDaoImpl implements AccountDao {private JdbcTemplate jdbcTemplate;&#64;Autowiredpublic void setDataSource(DataSource ds){this.jdbcTemplate &#61; new JdbcTemplate(ds);}public void transOut(Long outId, int money) {String sql &#61; "UPDATE account SET balance &#61; balance - ? WHERE id &#61; ?";jdbcTemplate.update(sql, money, outId);}public void transIn(Long inId, int money) {String sql &#61; "UPDATE account SET balance &#61; balance &#43; ? WHERE id &#61; ?";jdbcTemplate.update(sql, money, inId);}
}&#64;Service
&#64;Transactional
public class AccountServiceImpl implements AccountService {&#64;Autowiredprivate AccountDao dao;public void trans(Long outId, Long inId, int money) {dao.transOut(outId, money);int a &#61; 1 / 0; // 抛出异常dao.transIn(inId, money);}&#64;Transactional(readOnly &#61; true)public void queryAll(){//TODO}
}

xml配置: 必须要配置 TX注解解析器!

<context:annotation-config/><context:component-scan base-package&#61;"com.sunny"/><bean id&#61;"txManager" class&#61;"org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name&#61;"dataSource" ref&#61;"dataSource"/>bean><tx:annotation-driven transaction-manager&#61;"txManager"/><context:property-placeholder location&#61;"classpath:db.properties"/><bean id&#61;"dataSource" class&#61;"com.alibaba.druid.pool.DruidDataSource"init-method&#61;"init" destroy-method&#61;"close"><property name&#61;"driverClassName" value&#61;"${jdbc.driverClassName}"/><property name&#61;"url" value&#61;"${jdbc.url}"/><property name&#61;"username" value&#61;"${jdbc.username}"/><property name&#61;"password" value&#61;"${jdbc.password}"/><property name&#61;"initialSize" value&#61;"${jdbc.initialSize}"/>bean>

对比
在这里插入图片描述

三、基于 纯注解(JavaConfig) 配置声明式事务

跳转到目录

  • &#64;Configuration标识当前类是Spring的一个配置类
  • &#64;ComponentScan替代xml中的
  • &#64;Import引入其他配置类,被引入的配置类可以不加&#64;Configuration注解
  • &#64;PropertySource&#xff1a;引入外部properties文件&#xff0c;注意加classpath:
  • &#64;Value对成员变量赋值
  • &#64;Bean将一个方法的返回值对象加入到Spring的容器当中管理
  • &#64;Qualifier可以使用在方法上&#xff0c;表明对应的形参引入/注入的对象类型

直接删除xml的配置文件,取而代之的是一个Config类
&#64;Transactional注解&#xff0c;取代tx标签
&#64;EnableTransactionManagement注解&#xff0c;开启事务注解

  • &#64;Configuration 标识当前类为一个配置类, 当前项目的配置类,好比是applicationContext.xml

  • &#64;Import(Xxx.class) 在主配置类中包含Xxx的配置类

  • &#64;PropertySource("classpath:db.properties") 读取配置文件

  • &#64;Bean("Xxx") 相当于 , Bean()中不写参数,默认就是该方法创建的对象; 该对象就被Spring容器所管理了
    在这里插入图片描述

该类是一个配置类&#xff0c;它的作用和bean.xml是一样的spring中的新注解Configuration作用&#xff1a;指定当前类是一个配置类细节&#xff1a;当配置类作为AnnotationConfigApplicationContext对象创建的参数时&#xff0c;该注解可以不写。ComponentScan作用&#xff1a;用于通过注解指定spring在创建容器时要扫描的包属性&#xff1a;value&#xff1a;它和basePackages的作用是一样的&#xff0c;都是用于指定创建容器时要扫描的包。我们使用此注解就等同于在xml中配置了:Bean作用&#xff1a;用于把当前方法的返回值作为bean对象存入spring的ioc容器中属性:name:用于指定bean的id。当不写时&#xff0c;默认值是当前方法的名称细节&#xff1a;当我们使用注解配置方法时&#xff0c;如果方法有参数&#xff0c;spring框架会去容器中查找有没有可用的bean对象。查找的方式和Autowired注解的作用是一样的Import作用&#xff1a;用于导入其他的配置类属性&#xff1a;value&#xff1a;用于指定其他配置类的字节码。当我们使用Import的注解之后&#xff0c;有Import注解的类就父配置类&#xff0c;而导入的都是子配置类PropertySource作用&#xff1a;用于指定properties文件的位置属性&#xff1a;value&#xff1a;指定文件的名称和路径。关键字&#xff1a;classpath&#xff0c;表示类路径下

Java代码

//&#64;Repository("accountDaoImpl")
&#64;Repository // 默认是 accountDaoImpl,相当于类名首字母小写,相当于
public class AccountDaoImpl implements AccountDao {private JdbcTemplate jdbcTemplate;&#64;Autowiredpublic void setDataSource(DataSource ds){this.jdbcTemplate &#61; new JdbcTemplate(ds);}public void transOut(Long outId, int money) {String sql &#61; "UPDATE account SET balance &#61; balance - ? WHERE id &#61; ?";jdbcTemplate.update(sql, money, outId);}public void transIn(Long inId, int money) {String sql &#61; "UPDATE account SET balance &#61; balance &#43; ? WHERE id &#61; ?";jdbcTemplate.update(sql, money, inId);}
}&#64;Service
&#64;Transactional
public class AccountServiceImpl implements AccountService {&#64;Autowiredprivate AccountDao dao;public void trans(Long outId, Long inId, int money) {dao.transOut(outId, money);//int a &#61; 1 / 0; // 抛出异常dao.transIn(inId, money);}
}

Java配置类

//当前项目的配置类,好比是applicationContext.xml
&#64;Configuration //标识当前类为一个配置类
&#64;Import(DataSourceConfig.class) //包含其他的配置类
&#64;ComponentScan("com.sunny") //IoC注解解析器
&#64;EnableTransactionManagement//事务注解解析器
public class JavaConfig {//创建事务管理的Bean&#64;Beanpublic DataSourceTransactionManager txManager(DataSource ds) {return new DataSourceTransactionManager(ds);}
}// 当前项目的连接池的配置类
&#64;Configuration
&#64;PropertySource("classpath:db.properties")
public class DataSourceConfig {// 将properties的内容注入到这些变量中&#64;Value("${jdbc.driverClassName}")private String driverClassName;&#64;Value("${jdbc.url}")private String url;&#64;Value("${jdbc.username}")private String username;&#64;Value("${jdbc.password}")private String password;&#64;Value("${jdbc.initialSize}")private int initialSize;//创建连接池的Bean&#64;Bean("dataSource")public DataSource dataSource() {DruidDataSource ds &#61; new DruidDataSource();ds.setDriverClassName(driverClassName);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);ds.setInitialSize(initialSize);return ds;}
}

测试类

&#64;RunWith(SpringJUnit4ClassRunner.class)
&#64;ContextConfiguration(classes&#61;JavaConfig.class)
public class SpringTxTest {&#64;Autowiredprivate AccountService service;&#64;Testpublic void test1(){service.trans(10086L, 10010L, 1000);}
}

成功!

使用纯注解和半注解和XML的对比图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

四、选择开发方式

跳转到目录
在这里插入图片描述


推荐阅读
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • r2dbc配置多数据源
    R2dbc配置多数据源问题根据官网配置r2dbc连接mysql多数据源所遇到的问题pom配置可以参考官网,不过我这样配置会报错我并没有这样配置将以下内容添加到pom.xml文件d ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • eclipse学习(第三章:ssh中的Hibernate)——11.Hibernate的缓存(2级缓存,get和load)
    本文介绍了eclipse学习中的第三章内容,主要讲解了ssh中的Hibernate的缓存,包括2级缓存和get方法、load方法的区别。文章还涉及了项目实践和相关知识点的讲解。 ... [详细]
  • HDFS2.x新特性
    一、集群间数据拷贝scp实现两个远程主机之间的文件复制scp-rhello.txtroothadoop103:useratguiguhello.txt推pushscp-rr ... [详细]
  • 本文介绍了如何清除Eclipse中SVN用户的设置。首先需要查看使用的SVN接口,然后根据接口类型找到相应的目录并删除相关文件。最后使用SVN更新或提交来应用更改。 ... [详细]
  • Spring学习(4):Spring管理对象之间的关联关系
    本文是关于Spring学习的第四篇文章,讲述了Spring框架中管理对象之间的关联关系。文章介绍了MessageService类和MessagePrinter类的实现,并解释了它们之间的关联关系。通过学习本文,读者可以了解Spring框架中对象之间的关联关系的概念和实现方式。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • SpringBoot整合SpringSecurity+JWT实现单点登录
    SpringBoot整合SpringSecurity+JWT实现单点登录,Go语言社区,Golang程序员人脉社 ... [详细]
author-avatar
mobiledu2502883183
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有