栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

对于Web MVC Spring应用程序,@ Transactional应该在控制器或服务上运行吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

对于Web MVC Spring应用程序,@ Transactional应该在控制器或服务上运行吗?

不需要

@Transactional
注释是应在控制器上还是在服务上进行,但通常它将在服务上执行,该服务将对一个应在一个ACID事务中逻辑执行的请求执行逻辑。

在典型的Spring MVC应用程序中,至少需要两个上下文:应用程序上下文和servlet上下文。上下文是一种配置。应用程序上下文保存与整个应用程序相关的配置,而Servlet上下文保存仅与你的servlet相关的配置。这样,servlet上下文是应用程序上下文的子级,并且可以引用应用程序上下文中的任何实体。反之则不成立。

用你的话说

@EnableTransactionManagement and only looks for @Transactional on beans in the same application context they are defined in. This means that, if you put annotation driven configuration in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services.

@EnableTransactionManagement@Transactional
@ComponentScan
注解中声明的包中查找Bean,但仅在
@Configuration
定义它们的上下文()中进行
WebApplicationContext
查找。因此,如果你有一个for容器
DispatcherServlet
(this is a servlet context),则将在你告诉它进行组件扫描的类中
@EnableTransactionManagemen
t查找
@Transactional
该上下文(
@Configuration
class)。

@Configuration@EnableTransactionManagement@ComponentScan(basePackages = "my.servlet.package")public class ServletContextConfiguration {    // this will only find @Transactional annotations on classes in my.servlet.package package}

由于你的@Service类是Application上下文的一部分,因此,如果你希望使它们具有事务性,则需要使用来

@Configuration
Application Context
的类添加注释
@EnableTransactionManagement

@Configuration@EnableTransactionManagement@ComponentScan(basePackages = "my.package.services")public class ApplicationContextConfiguration {    // now this will scan your my.package.services package for @Transactional}

ContextLoaderListener
实例化
DispatcherServlet
时,将你的
Application Context
配置与和Servlet Context配置一起使用。(如果你尚未执行完整的基于Java的配置,请参阅javadoc,而不是xml。)

附录:

@EnableTransactionManagement
具有与
<tx:annotation-driven />
Java配置相同的行为。在此处检查是否
ContextLoaderListener
与XML 一起使用。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/383207.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号