今天,使用@Transactional,但是事务却不起作用,配置确定配置成功,在网上查找资料,在每个每个原因都试了之后仍然无效,最终发现,原来他们都漏了一个原因,而我正好是这个原因。
因为spring容器和spring-mvc是父子容器,spring容器会先加载,如果此时扫描了Controller,但未扫描到Service。
spring事务配置文件还有上下文都是通过org.springframework.web.context.ContextLoaderListener加载的,而spring MVC的action是通过org.springframework.web.servlet.DispatcherServlet加载的 。
web是先启动ContextLoaderListener后启动DispatcherServlet 在ContextLoaderListener加载的时候action并没在容器中,所以现在使用AOP添加事务或者扫描注解都是无用的。
结论:让spring扫描注册Service实现类,让MVC扫描注册Controller,此时spring父容器已经注册Service为Bean,此时事务可以得到正常配置。