spring的父子上下文容器及配置

本文由做者張遠道受權網易雲社區發佈。html

spring父子容器
spring總的上下文容器有父子之分。父容器和子容器。父容器對子容器可見,子容器對父容器不可見。web

對於傳統的spring mvc來講,spring mvc容器爲子容器,也就是說ServletDispatcher對應的容器爲子容器,而web.xml中經過ConextLoaderListener的contextConfigLocation屬性配置的爲父容器。spring

使用場景
父子容器的主要用途之一即是是上下文隔離。考慮如下一種場景。數據庫

project-service.jar爲服務層模塊。包含一些數據庫service方法。起對應的spring配置文件爲project-service.xml。 project-api爲api服務器代碼。它依賴於project-service.jar。 可是,project-api須要對project-service裏的某些方法進行decorate,進行裝飾,好比給CustomerService進行裝飾。裝飾後的類爲CachedCustomerService。因而,如今project-api裏面包含兩個CustomerService,一個是來自project-service的CustomerService,另外一個是CachedCustomerService。這個時候,若是project-api工程全部的配置文件都經過一個上下文進行加載,勢必出現問題。由於,project裏的PayService裏經過@Resource標準注入了CustomerService,相似以下api

@Serivcepublic class PayService{@Resourceprivate CustomerService cusService;服務器

}
這時,因爲上下文在注入customerService屬性的時候,遇到了兩個CustomService。它沒法判讀注入哪一個Service。 固然了,有人會說,改一下PayService的Resource屬性,指定下具體注入哪一個。可是,project-service.jar是第三方庫的話,改動代碼變得不可行,除非拿到源碼。mvc

配置父子容器
這個時候,就能夠經過父子容器的方式解決這個問題。 將project-service放在父容器中,project-api全部的bean用子容器加載。app

假設project-api的上下文配置文件爲project-api.xml,實現方法以下。spa

一、定義project-total.xmlcode

<bean id = "serviceContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <constructor-arg>
    <value>
        classpath:project-service.xml        </value>
    </constructor-arg>
</bean>


<bean id = "apiContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <constructor-arg>
        <value>
            classpath:project-api.xml            </value>
    </constructor-arg>

    <constructor-arg>
        <ref bean="serviceContext"/>
    </constructor-arg>
</bean>

二、在web.xml的上下文配置中以下。

<context-param> 
    <param-name>contextConfigLocation</param-name>
    <param-value> classpath*:project-total.xml</param-value>  
</context-param>


<listener>   
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>   
  </listener>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

說明,其中,serviceContext爲父容器,apiContext爲子容器。在apiContext掃描路徑裏的任務bean都對serviceContext不可見。從而達到隔離的目的

參考列表

http://springtips.blogspot.co...

http://docs.spring.io/autorep...

更多網易技術、產品、運營經驗分享請訪問網易雲社區。

文章來源: 網易雲社區

相關文章
相關標籤/搜索