@Order 可以应用于@Transactional 吗?

can @Order be applied on @Transactional?

我有一个用@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,所以首先创建我的事务然后执行建议吗?

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

是的,在@Configurationclass中使用:

@EnableTransactionManagement(order = Ordered.HIGHEST_PRECEDENCE)

或您需要的任何顺序

我猜@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() {}
}