• spring和springmvc父子容器关系


    一般来说,我们在整合spring和SpringMVC这两个框架中,web.xml会这样写到:

    <!-- 加载spring容器 -->
      <!-- 初始化加载application.xml的各种配置文件 -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml</param-value>
      </context-param>
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
    
      <!-- 配置springmvc前端控制器 -->
      <servlet>
        <servlet-name>taotao-manager</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation,
         springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/applicationContext-MVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>

    首先配置的是Spring容器的初始化加载的application文件,然后是SpringMVC的前端控制器(DispatchServlet),当配置完DispatchServlet后会在Spring容器中创建一个新的容器。其实这是两个容器,Spring作为父容器,SpringMVC作为子容器。SpringMVC的子容器是可以访问父容器Spring对象的

    我们按照官方推荐根据不同的业务模块来划分不同容器中注册不同类型的Bean:Spring父容器负责所有其他非@Controller注解的Bean的注册,而SpringMVC只负责@Controller注解的Bean的注册,使得他们各负其责、明确边界。配置方式如下

      1.在applicationContext.xml中配置:

    <!-- Spring容器中注册非@controller注解的Bean -->
    <context:component-scan base-package="com.hafiz.www">

       <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

    </context:component-scan>

      2.applicationContext-MVC.xml中配置

    <!-- SpringMVC容器中只注册带有@controller注解的Bean -->
    <context:component-scan base-package="com.hafiz.www" use-default-filters="false">

       <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />

    </context:component-scan>

    疑问1 单利的bean在父子容器中是一个实例还是两个实例

        答:初始化两次,Spring 容器先初始化bean,MVC容器再初始化bean,所以应该是两个bean。

    疑问2为什么不用spring加载所有的bean

      答: SpringMVC容器中没有对象,没有对象就没有Controller,所以加载处理器,适配器的时候就会找不到映射对象,映射关系

    为什么不用springmvc加载所有的对象

       答: 网上很多文章说子容器不支持AOP,其实这是不对的。因为正常会有AOP的相关配置都在Spring容器中配置,如果都迁移到MVC配置文件,则所有bean都在子容器中,相当于只有一个容器了,所以也就实现了AOP。缺点是不利于扩展。


    作者:
    链接:http://www.imooc.com/article/16155
    来源:慕课网
    本文原创发布于慕课网 ,转载请注明出处,谢谢合作


    作者:
    链接:http://www.imooc.com/article/16155
    来源:慕课网
    本文原创发布于慕课网 ,转载请注明出处,谢谢合作


    作者:
    链接:http://www.imooc.com/article/16155
    来源:慕课网
    本文原创发布于慕课网 ,转载请注明出处,谢谢合作

  • 相关阅读:
    Nginx配置文件详解
    JVM调优—性能分析神器-JProfiler详解
    Navicat Premium 15破解
    Nginx配置反向代理,负载均衡,动静分离,高可用
    Nginx安装和常用命令
    Spring中ApplicationContextAware的作用
    java中发起http和https请求
    MySql高可用架构
    matlab画3维meshgrid/plot3/mesh/surf的用法
    如何规范地编写一个MATLAB函数文件
  • 原文地址:https://www.cnblogs.com/moxiaotao/p/9246667.html
Copyright © 2020-2023  润新知