简体   繁体   English

@transactional 服务在 spring 中应该是单例还是原型?

[英]Should @transactional services be singleton or prototype in spring?

Will transaction management be a problem in spring if the service layer class is singleton?如果service层类是singleton,事务管理会不会是spring的问题? Or should it be prototype?还是应该是原型?

No that should not be a problem.不,这应该不是问题。 What the @Transactional annotation will do is bind the Transaction lifecyle to the current thread. @Transactional注释会做的是将事务生命周期绑定到当前线程。 So each new thread will be run in a separate transaction.因此,每个新线程都将在单独的事务中运行。

So when your method is invoked, Spring will wrap that method call into a Transaction, so in a single threaded context, a transaction will start and commit if the invocation is successful, and rollback (depending on your config) if an exception is thrown.因此,当您的方法被调用时,Spring 会将该方法调用包装到一个事务中,因此在单线程上下文中,如果调用成功,则事务将启动并提交,如果抛出异常,则回滚(取决于您的配置)。

In a multithreaded context, each Thread will run in a separate transaction.在多线程上下文中,每个线程将在单独的事务中运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM