现在的位置: 首页 > 编程语言 > 正文

Spring事务annotation原理详解

2020年02月13日 编程语言 ⁄ 共 1309字 ⁄ 字号 评论关闭

这篇文章主要介绍了Spring事务annotation原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

在使用Spring的时候,配置文件中我们经常看到 annotation-driven 这样的注解,其含义就是支持注解,一般根据前缀 tx、mvc 等也能很直白的理解出来分别的作用。

<tx:annotation-driven/> 就是支持事务注解的(@Transactional) 。

<mvc:annotation-driven> 就是支持mvc注解(Controller中可以使用MVC的各种注解)。

<tx:annotation-driven/> 会有一个属性来指定使用哪个事务管理器,如:

<tx:annotation-driven transaction-manager="txManager" />//txManager就是指定的事务管理器

这样逐层引用下去,所以我们使用@Transactionl 注解可以控制事务就通俗易懂了。

另外要提一下的就是 Spring 是使用 aop 通过 asm 操作Java字节码的方式来实现对方法的前后事务管理的。

那我们是否就可以在程序中所有被spring管理的类上都可以使用@Transactional注解了呢,在Service上可以使用@Transactional 注解这个是肯定的了,那总有些人也想弄明白能否在Controller 使用?答案显然是“不一定”的(与时间配置有关),下面做下解释:

在 spring-framework-reference.pdf 文档上有这样一段话:

<tx:annotation-driven/> only looks for @Transactional on beans in the same application contextit is defined in. This means that, if you put <tx:annotation-driven/> in a WebApplicationContextfor a DispatcherServlet, it only checks for @Transactional beans in your controllers,and not your services.

翻译:<tx:annoation-driven/>只会查找和它在相同的应用上下文件中定义的bean上面的@Transactional注解,如果你把它放在Dispatcher的应用上下文中,它只检查控制器(Controller)上的@Transactional注解,而不是你services上的@Transactional注解。

所以,可以确定的是我们是可以在Controller上使用事务注解的,但是我们不推荐这样做,这里只是为了说明spring对<tx:annotation-driven/>的使用。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: Spring事务annotation原理详解

以上就上有关Spring事务annotation原理详解的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.