[英]Spring @Transactional and @Service
I'm working in a company where JPA @transactional are used within @Component beans.我在一家公司工作,该公司在 @Component bean 中使用了 JPA @transactional。 I've always been told that @Transactional should be used inside @Service beans.我一直被告知 @Transactional 应该在 @Service bean 中使用。 Does someone could explain spring mechanisms differences between those and what are the best pratctices.. and why有人可以解释 spring 机制之间的差异以及最佳实践是什么......以及为什么
There is no difference.没有区别。
Also, @Service
and @Component
are the same.此外, @Service
Service 和@Component
是相同的。 @Service
is just a stereotype that developers often use to indicate that the Spring Bean is kind of a Service (maybe in a DDD meaning or not) @Service
只是开发人员经常用来表示 Spring Bean 是一种服务的一种刻板印象(可能是 DDD 的意思)
First of all, there is no difference.首先,没有区别。 From the spring javadoc来自 spring javadoc
@Component @零件
Indicates that an annotated class is a "component".表示带注释的 class 是“组件”。 Such classes are considered candidates for auto-detection when using annotation-based configuration and classpath scanning.当使用基于注释的配置和类路径扫描时,此类类被认为是自动检测的候选对象。 ... ...
@Transactional @Transactional
Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state."表示带注释的 class 是“服务”,最初由域驱动设计(Evans,2003 年)定义为“作为独立于 model 的接口提供的操作,没有封装的 Z9ED39E2EA931586B73E92”。 May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar.也可能表明 class 是“业务服务外观”(在核心 J2EE 模式意义上)或类似的东西。 This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use it as appropriate.此注释是通用的刻板印象,各个团队可能会缩小其语义并酌情使用它。 This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.这个注解作为@Component 的一个特化,允许通过类路径扫描自动检测实现类。
Frankly speaking, they behave in the same way.坦率地说,他们的行为方式相同。
By using @Transactional annotation on a public method or class it simply creates a proxy with transaction code for you.通过在公共方法或 class 上使用 @Transactional 注释,它只需为您创建带有事务代码的代理。
IMO great explanation of @Transactional IMO 对@Transactional 的精彩解释
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.