不需要
@Transactional注释是应在控制器上还是在服务上进行,但通常它将在服务上执行,该服务将对一个应在一个ACID事务中逻辑执行的请求执行逻辑。
在典型的Spring MVC应用程序中,至少需要两个上下文:应用程序上下文和servlet上下文。上下文是一种配置。应用程序上下文保存与整个应用程序相关的配置,而Servlet上下文保存仅与你的servlet相关的配置。这样,servlet上下文是应用程序上下文的子级,并且可以引用应用程序上下文中的任何实体。反之则不成立。
用你的话说
@EnableTransactionManagement and only looks for @Transactional on beans in the same application context they are defined in. This means that, if you put annotation driven configuration in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services.
@EnableTransactionManagement@Transactional在
@ComponentScan注解中声明的包中查找Bean,但仅在
@Configuration定义它们的上下文()中进行
WebApplicationContext查找。因此,如果你有一个for容器
DispatcherServlet(this is a servlet context),则将在你告诉它进行组件扫描的类中
@EnableTransactionManagement查找
@Transactional该上下文(
@Configurationclass)。
@Configuration@EnableTransactionManagement@ComponentScan(basePackages = "my.servlet.package")public class ServletContextConfiguration { // this will only find @Transactional annotations on classes in my.servlet.package package}由于你的@Service类是Application上下文的一部分,因此,如果你希望使它们具有事务性,则需要使用来
@Configuration为
Application Context的类添加注释
@EnableTransactionManagement。
@Configuration@EnableTransactionManagement@ComponentScan(basePackages = "my.package.services")public class ApplicationContextConfiguration { // now this will scan your my.package.services package for @Transactional}ContextLoaderListener实例化
DispatcherServlet时,将你的
Application Context配置与和Servlet Context配置一起使用。(如果你尚未执行完整的基于Java的配置,请参阅javadoc,而不是xml。)
附录:
@EnableTransactionManagement具有与
<tx:annotation-driven />Java配置相同的行为。在此处检查是否
ContextLoaderListener与XML 一起使用。



