Spring和SpringMVC整合

对于Spring和SpringMVC进行整合不一定需要:

1.对于不需要整合的做法,即不需要在web.xml中配置配置启动 Spring IOC 容器的 ContextLoaderListener ,只需web.xml配置springmvc的DispatcherServlet时,采用通配符的形式导入其他配置符。这个方法简单且不会出现bean对象被初始化两次的结果。其还有一种方式,就是直接在Springmvc的配置文件中通过<import>标签导入其他ioc容器,整合成一个ioc

代码如下:

<!-- 配置DispatcherServlet -->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置springMVC需要加载的配置文件,这里直接通过通配符将所有spring的IOC一同配置进来,不需要再配置ContextLoaderListener-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-*.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <!-- 匹配所有请求,此处也可以配置成 *.do 形式 -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

2.对于spring和springmvc的采取整合的形式,就要在web.xml中配springmvc的DispatcherServlet同时也要配ContextLoaderLister


	<!-- 配置启动 Spring IOC 容器的 Listener -->
	<!-- needed for ContextLoaderListener -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:beans.xml</param-value>
	</context-param>

	<!-- Bootstraps the root web application context before servlet initialization -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	

配置后这里将导入两个ioc容器导入,通常这两个ioc中有些bean是重合的。在启动项目后就会出现,同一个对象被初始化两次,好较大的性能。应就要为不同的ioc容器配置彼此容器的内容界限。其配置如下:

在springmvc配置文件中
<context:component-scan base-package="com.atguigu.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>
<!--指定扫描的指定bean对象-->
beans文件中
<context:component-scan base-package="com.atguigu.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>

	<!-- 配置数据源, 整合其他框架, 事务等. -->

注:这两个ioc容器间由包含其父子关系,springmvc的ioc相对于beans的ioc为子,beans为父。

因此,父ioc中的bean不能应用springmvcioc中的bean,其用@Autwire将会为null

但springmvc中的bean能引用beans的bean对象

猜你喜欢

转载自blog.csdn.net/weixin_39573518/article/details/89055291