首页 > 技术文章 > spring context 继承

allenwas3 2018-05-25 17:27 原文

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  
       <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/servlet-example.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
</web-app>

上面的配置文件定义了 2 个 WebApplicationContext,前一个容器的配置文件是 applicationContext.xml, 后一个容器的配置文件是 servlet-example.xml,前者是后者的 parent。

手动创建父子容器:

ClassPathXmlApplicationContext appCtx = 
        new ClassPathXmlApplicationContext("parent.xml");

// 指定父容器
ClassPathXmlApplicationContext childCtx = 
        new ClassPathXmlApplicationContext(new String[]{"child.xml"}, appCtx);

现象:子容器可以获得父容器中的 bean,反之不能。

推荐阅读