Home > Mobile >  Spring @Transactional and @Service
Spring @Transactional and @Service

Time:08-31

I'm working in a company where JPA @transactional are used within @Component beans. I've always been told that @Transactional should be used inside @Service beans. Does someone could explain spring mechanisms differences between those and what are the best pratctices .. and why

CodePudding user response:

There is no difference.

Also, @Service and @Component are the same. @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)

CodePudding user response:

First of all, there is no difference. From the spring javadoc

@Component

Indicates that an annotated class is a "component". Such classes are considered candidates for auto-detection when using annotation-based configuration and classpath scanning. ...

@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." May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar. 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.

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.

IMO great explanation of @Transactional

Spring Stereotype Annotations

  • Related