Spring整合SpringMVC
Spring是否需要整合SpringMVC吗?例如:
1.是否需要加入Spring的IOC容器?
2.是否需要在web.xml
文件中配置启动Spring IOC
容器的ContextLoaderListener
?
需要:通常情况下,例如数据源,事务,整合其他框架都是放在Spring的配置文件中(而不是放在SpringMVC的配置文件中)。实际上,放入Spring配置文件对应的IOC容器中还有Service和Dao。
不需要:都放在SpringMVC的配置文件中。也可以分多个Spring的配置文件,然后使用import节点导入其他的配置文件。
推荐使用Spring的配置文件。
可能会出现的问题:
若Spring的IOC容器和SpringMVC的IOC容器扫描的包有重合的部分,就会导致有bean的会被创建2次。
如何解决?
1.使Spring的IOC容器扫描的包和SpringMVC的IOC容器扫描的包没有重合的部分。
2.使用
<context:exclude-filter type="annotation" expression=""/>
<context:include-filter type="annotation" expression=""/>
如下,SpringMVC配置文件中,把use-default-filters="false"
,只扫描Controller
和ControllerAdvice
注解。
<context:component-scan base-package="com.springmvc" use-default-filters="false">
<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>
在Spring的配置文件中,不扫描Controller
和ControllerAdvice
注解。
<context:component-scan base-package="com.springmvc">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
Spring IOC 容器和 SpringMVC IOC 容器的关系
SpringMVC的IOC容器中的bean可以引用Spring的IOC容器中的bean。反之则不行,Spring IOC容器中的bean不能引用SpringMVC的IOC容器中的bean。
SpringMVC对比Struts2
1.SpringMVC的入口是Servlet,而struts2是Filter。
2.SpringMVC会稍微被Struts2快些,SpringMVC是基于方法设计的,而struts2是基于类,每次发一次请求都会实例一个Action
3.SpringMVC使用更加简洁,开发效率SpringMVC确实比struts2高:支持JSR303,处理ajax的请求更方便。
4.struts2的OGNL表达式使页面的开发效率比SpringMVC更高些。