Where should I put @Transactional annotation: at an interface definition or at an implementing class?

后端 未结 5 1395
花落未央
花落未央 2020-11-29 17:53

The question from the title in code:

@Transactional (readonly = true)
public interface FooService {
   void doSmth ();
}


public class FooServiceImpl implem         


        
5条回答
  •  借酒劲吻你
    2020-11-29 18:23

    Spring's recommendation is that you annotate the concrete implementations instead of an interface. It's not incorrect to use the annotation on an interface, it's just possible to misuse that feature and inadvertently bypass your @Transaction declaration.

    If you've marked something transactional in an interface and then refer to one of its implementing classes elsewhere in spring, it's not quite obvious that the object that spring creates will not respect the @Transactional annotation.

    In practice it looks something like this:

    public class MyClass implements MyInterface { 
    
        private int x;
    
        public void doSomethingNonTx() {}
    
        @Transactional
        public void toSomethingTx() {}
    
    }
    

提交回复
热议问题