Spring 事务和 AOP 代理

Spring Transactions and AOP proxies

在许多文章中,我读到以下内容“Spring 的声明式事务是通过 AOP 代理启用的”。

对于像我这样的新手,这到底是什么意思?

我可以在哪种 类 或 bean 上使用 @Transactional 注释?

我是否必须在 POM.xml 中添加 Maven 依赖项“spring-aop”?

是否明确需要 @EnableTransactionManagement 才能使事务正常工作?

已经有 an answer 详细介绍了 @Transactional 的作用及其工作原理。

关于您的其他问题。

On what kind of classes or beans can I use the @Transactional annotation?

理论上每个 class 你想要的。你应该这样做吗?例如,创建您的 web 层,事务边界通常被认为是一个坏主意,因为您的服务层应该是事务边界。

Do I have to add the maven dependency spring-aop in pom.xml ?

没有。 spring-tx 依赖项本身已经将其引入。当使用 spring-boot-starter-data-jpa(或另一个与持久性相关的)时,它也会自动包含。

Is @EnableTransactionManagement explicitly needed in order to make the transaction work?

视情况而定。一般来说,在 Spring Boot 应用程序中你不需要添加它,因为 Spring Boot 会自动启用它。如果你不使用 Spring Boot 而只是一个普通的 Spring 应用程序,你需要在使用 XML 告诉 [=35] 时添加 @EnableTransactionManagement<tx:annotation-driven> =] 来处理 @Transactional 个注释。