【问题标题】:can @Order be applied on @Transactional?@Order 可以应用于@Transactional 吗?
【发布时间】:2016-05-29 09:03:51
【问题描述】:

我有一个用@Transactional 注释的方法和另一个自定义注释@Custom。这个自定义注解被包裹在一个通知周围。操作顺序如下:

1.Transactional method gets called
2.Sees @Transactional and @Custom
3.As @Custom is intercepted by around advice, it first executes code before invocation of method
4.invocationContext.proceed()
5.Transaction gets created
6.Actual method runs
7.Back to around advice and executes code after method invocation

我想在调用通知之前创建事务。如下:

1.Transactional method gets called
2.Sees @Transactional and @Custom
3.Transaction gets created (propagate this transaction to @Custom)
4.As @Custom is intercepted by around advice, it first executes code before invocation of method
5.invocationContext.proceed()
6.Actual method runs
7.Back to around advice and executes code after method invocation

这样建议和方法都在同一个事务中

我们可以在@Transactional 上使用@Order,所以首先要创建我的事务然后执行建议?

【问题讨论】:

    标签: spring spring-aop spring-transactions


    【解决方案1】:

    是的,在@Configuration 类中使用:

    @EnableTransactionManagement(order = Ordered.HIGHEST_PRECEDENCE)
    

    或您需要的任何顺序

    【讨论】:

      【解决方案2】:

      我猜@EnableTransactionManagement(order = Ordered.HIGHEST_PRECEDENCE) 是全局配置。

      如果你只想要@Transactional这个方法A(),而不是其他方法,也许你可以定义方法B()来调用A()。这种方式会指出注解的顺序。

      像这样:

      // I think this is not a smart solution. 
      // If you have a good idea, please let me know.
      
      @Service
      class TestB {
          @Autowired
          private TestA testA;
      
      
          @Transactional
          public void b() {
              // !! notice: you should call bean testA that will use spring's AOP
              testA.a();
          }
      }
      
      @Service
      class TestA {
          @Custom
          public void a() {}
      }
      
      

      【讨论】:

        【解决方案3】:

        您可以尝试在 @custom annotation 之上添加 @transaction(propagation=required)。它可能会起作用

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-25
          • 1970-01-01
          • 2012-02-21
          • 1970-01-01
          • 1970-01-01
          • 2012-01-01
          • 1970-01-01
          • 2023-02-17
          相关资源
          最近更新 更多