问题描述
由于程序员被迫捕获所有已检查的异常,因此如果出现任何问题,我将抛出已检查的异常.我想回滚这些期望中的任何一个.在每个 @Transactional
注释上编写 rollbackFor=Exception.class
非常容易出错,所以我想告诉 spring:每当我写 @Transactional
,我的意思是 @Transactional(rollbackFor=Exception.class)
".
我知道,我可以创建自定义注释,但这似乎不自然.
那么有没有办法告诉 spring 它应该如何全局处理已检查的异常?
自定义快捷方式注释
我知道,我可以创建自定义注释,但这似乎不自然.
不,这正是自定义注释的用例.这是引用自 Spring 参考中的>自定义快捷方式注释:
如果你发现你反复使用相同的属性@Transactional 在许多不同的方法,然后是 Spring 的元注解支持允许您定义自定义您特定的快捷方式注释用例.
示例代码
这是您的用例的示例注释:
@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Transactional(rollbackFor=Exception.class)公共@interface MyAnnotation {}
现在用 @MyAnnotation
注释你的服务和/或方法(你会想到一个更好的名字).这是经过充分测试的默认功能.为什么要重新发明轮子?
Since the programmer is forced to catch all checked exception, I to throw checked exception in case of any problem. I would like to rollback on any of those expections. Writing rollbackFor=Exception.class
on every @Transactional
annotation is very error-prone, so I would like to tell spring, that: "whenever I write @Transactional
, I mean @Transactional(rollbackFor=Exception.class)
".
I know, that I could create a custom annotation, but that seems unnatural.
So is there a way to tell spring how it should handle checked excpetions globally?
Custom Shortcut Annotations
No, this is exactly the use case for a Custom Annotation. Here's a quote from Custom Shortcut Annotations in the Spring Reference:
Sample Code
And here's a sample annotation for your use case:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(rollbackFor=Exception.class)
public @interface MyAnnotation {
}
Now annotate your services and / or methods with @MyAnnotation
(you'll think of a better name). This is well-tested functionality that works by default. Why re-invent the wheel?
这篇关于每当我说@Transactional 时,回滚每个已检查的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!