有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

每当我说@Transactional时,java都会对每个选中的异常进行回滚

由于程序员被迫捕获所有已检查的异常,因此我必须在出现任何问题时抛出已检查的异常。我想回过头来看看这些期待中的任何一个。在每个@Transactional注释上写rollbackFor=Exception.class非常容易出错,所以我想告诉spring:“每当我写@Transactional,我的意思是@Transactional(rollbackFor=Exception.class)

我知道,我可以创建自定义注释,但这似乎不自然

那么,有没有办法告诉spring它应该如何在全球范围内处理已检查的例外情况呢


共 (2) 个答案

  1. # 1 楼答案

    自定义快捷方式注释

    I know, that I could create a custom annotation, but that seems unnatural.

    不,这正是自定义注释的用例。这里引用了Spring参考中的Custom Shortcut Annotations

    If you find you are repeatedly using the same attributes with @Transactional on many different methods, then Spring's meta-annotation support allows you to define custom shortcut annotations for your specific use cases.

    示例代码

    下面是针对您的用例的示例注释:

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Transactional(rollbackFor=Exception.class)
    public @interface MyAnnotation {
    }
    

    现在用@MyAnnotation注释您的服务和/或方法(您会想到一个更好的名称)。这是经过良好测试的默认功能。为什么要重新发明轮子

  2. # 2 楼答案

    看起来您可以根据方法名称配置事务性建议,如下所示: (来自the Spring 2.0 docs

    Exactly which Exception types mark a transaction for rollback can be configured. Find below a snippet of XML configuration that demonstrates how one would configure rollback for a checked, application-specific Exception type.

    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
          <tx:method name="get*" read-only="false" rollback-for="NoProductInStockException"/>
          <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>