SpringMVC Controller配置和事务问题


Java框架: SpringMVC4 , Spring4

Spring配置文件通过web.xml引入

SpringMVC配置文件: app-servlet.xml


 <context:component-scan base-package="com.xxx.controller">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

说明: 配置文件要求Controller类是写在com.xxx.controller包的,并且需要@Controller注解。
此时是可以在正常在Controller中注入IOC提供的service对象,并且有完整的事务,实现数据操作。

问题来了:

我修改了app-servlet.xml,把base-packet定义为com.xxx,如下


 <context:component-scan base-package="com.xxx">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

修改之后,controller继续提供URL访问服务,可以查询到数据,但是 无法进行DELETE、UPDATE操作 了!这是为什么呢?

为什么可以访问URL,可以查询数据,但是无法修改和删除了呢??
内部的原理是怎么回事呢?


感谢 @1away 的回答。
原来是controller类被SpringMVC和SpringIoC容器重复扫描的问题。
修改配置后,IoC不扫描controller所在包就可以了。
可以明确指定路径,也可以通过exclude-filter解决.
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

java transaction 事务 spring springMVC

khxooo 8 years, 10 months ago

我都是这样配置的,没有问题啊

金君君馆长 answered 8 years, 10 months ago

我是这样配的没有问题,
dispatcherServlet配置 mvc-config.xml


 <!-- 使用Annotation自动注册Bean,只扫描@Controller -->
    <context:component-scan base-package="com.mxmht.xxx" use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

contextConfigLocation 配置spring-context.xml


 <!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  -->
    <context:component-scan base-package="com.mxmht.xxx"><!-- base-package 如果多个,用“,”分隔 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

这个就相当于base-package="com.mxmht.xxx" 楼上的com.xxx

寒冰射手琪露诺 answered 8 years, 10 months ago

Your Answer