关于spring注解@Transactional使用注意点

  • 在配置类(例:ApplicationConfig)上@Configuration,@EnableTransactionManagement

The @EnableTransactionManagement annotation provides equivalent support if you are using Java based configuration. Simply add the annotation to a@Configuration class. See the javadocs for full details.

  • 尽量在具体实现类某个公开的方法(public)上加@Transactional

 

  • 尽管官网说明可以把@Transactional 加在接口或接口方法上,但官方更推荐在具体实现类或公开方法上加事务

You can place the @Transactional annotation before an interface definition, a method on an interface, a class definition, or a public method on a class. However, the mere presence of the @Transactional annotation is not enough to activate the transactional behavior. The @Transactional annotation is simply metadata that can be consumed by some runtime infrastructure that is @Transactional-aware and that can use the metadata to configure the appropriate beans with transactional behavior. In the preceding example, the <tx:annotation-driven/> element switches on the transactional behavior.

 

Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the @Transactional annotation, as opposed to annotating interfaces. You certainly can place the @Transactional annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies ( proxy-target-class="true") or the weaving-based aspect ( mode="aspectj"), then the transaction settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly bad.

猜你喜欢

转载自zhijund.iteye.com/blog/2226196