Generally, we configure transaction management for Service layer code in Spring's configuration file application.xml. We can AOP enhancement of Service methods or transaction processing such as transaction rollback. However, when we encounter a problem, if the Service layer method is called in the Controller class, the configured transaction management will be invalid. If we query relevant information and find the reason. In fact, Spring and SpringMVC are parent-child relationships, Spring is parent containers, and SpringMVC is child containers. In other words, the application.xml should be responsible for scanning the annotations of @Controller such as @Service, while the SpringMVC configuration file should only be responsible for scanning the @Controller, otherwise it will cause repeated scans to cause the transactions configured in the Spring container to be invalid.
Therefore, the correct configuration method should be:
Spring configuration file: application.xml
<context:component-scan base-package="org.bc.redis" use-default-filters="true"> <!-- Exclude classes with @Controller annotation--> <context:exclude-filter type="annotation" expression="org.bc.redis.controller.UserController"/> </context:component-scan>
or
<!-- Specify the scanned package, avoid packages containing @Controller annotation--> <context:component-scan base-package="org.bc.redis.service" use-default-filters="true"> </context:component-scan>
SpringMVC configuration file: springmvc.xml
<!-- Scan only packages with @Controller annotation to avoid repeated scans --> <context:component-scan base-package="org.bc.redis.controller" use-default-filters="true"> </context:component-scan>
at last
After testing, the main problem is that SpringMVC's configuration file scans the package scope. Even if Spring's configuration file scans the @Controller annotation, it will be rescanned once in SpringMVC. As long as the transaction management service is not rescanned, there will be no transaction failure problem.
Summarize
The above is all the content of this article about the reasons and solutions for the invalid transaction management of Spring+SpringMVC configuration. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!