Does Spring @transaction work on a specific abstract class method

From spring reference document

Spring recommends only annotating specific classes (and methods of specific classes) with @Transactional annotation, rather than annotating interfaces. Of course, you can put the @Transactional annotation on an interface (or an interface method), but this only works as you would expect if you use an interface-based proxy. The fact that Java annotations are not inherited from interfaces means that if you use proxy classes (proxy-target-class = "true") or an aspect based on weaving (mode = "aspectj"), then transaction settings are not recognized proxy and weave infrastructure, and the object will not be wrapped in a transactional proxy, which will be clearly bad.

Although it is only about interfaces, abstract classes are also considered unsafe.

So, if I have an abstract class

public abstract class BaseService{ //here is a concrete method @Transactional public void updateData{ //do stuff using dao layer } 

and a specific class that extends the class

 public class SpecialService extends BaseService{ //body of class } 

Now, if I call specialService.updateData() from my controller class, will it be transactional?

+6
source share
1 answer

Providing that you really set up Spring transaction management correctly using @Transactional in an abstract superclass will be , since @Transactional itself is annotated using @Inherited and from it we have Javadoc :

Indicates that the annotation type is automatically inherited. If the Inherited meta annotation is present in the annotation type declaration, and the user requests an annotation type in the class. The declaration and class declaration do not contain annotations for this type, then the superclass class will be automatically requested for the annotation type. This process will be repeated until the annotation for this type, or the top of the class hierarchy (Object) is reached. If the superclass does not have an annotation for this type, the query indicates that this class does not have such an annotation.

Note that this type of meta annotation does not work if the annotated type is used to annotate anything but the class. We also note that this meta annotation only leads to the inheritance of annotations from the superclass; annotations on implemented interfaces do not affect.

To see that @Transactional annotated with @Inherited , check out Javadoc

+8
source

Source: https://habr.com/ru/post/969517/


All Articles