[轉]Spring IOC父子容器簡介

來源:互聯網
上載者:User

標籤:cep   tor   外掛程式   set   一個   hiera   span   有一個   style   

通過HierarchicalBeanFactory介面,Spring的IoC容器可以建立父子層級關聯的容器體系,子容器可以訪問父容器中的Bean,但父容器不能訪問子容器的Bean。在容器內,Bean的id必須是唯一的,但子容器可以擁有一個和父容器id相同的Bean。父子容器層級體系增強了Spring容器架構的擴充性和靈活性,因為第三方可以通過編程的方式,為一個已經存在的容器添加一個或多個特殊用途的子容器,以提供一些額外的功能。 

Spring使用父子容器實現了很多功能,比如在Spring MVC中,展現層Bean位於一個子容器中,而業務層和持久層的Bean位於父容器中。這樣,展現層Bean就可以引用業務層和持久層的Bean,而業務層和持久層的Bean則看不到展現層的Bean。

應用舉例
Runner.java

//這個類負責啟動父容器public class Runner {    public static void main(String[] args){        ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:/spring1.xml");    }}

PluginLoader.java

public class PluginLoader implements ApplicationContextAware {    ApplicationContext parentApplicationContext;    ConfigurableApplicationContext childContext;    public void load() {      //掃描所有classpath下面的以plugin_開頭spring的設定檔進行裝配,這裡約定所有的子容器外掛程式都必須有一個以plugin_開頭的設定檔,並通過這個檔案被父容器載入        childContext = new ClassPathXmlApplicationContext("classpath*:/plugin_*.xml");        childContext.setParent(parentApplicationContext);        childContext.refresh();    }    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        this.parentApplicationContext = applicationContext;    }}

可以看到父容器(spring1.xml):

<bean id="parentClass" class="com.test1.ParentClass"></bean><bean id="pluginLoader" class="com.test1.PluginLoader" init-method="load"></bean>

子容器(plugin_1.xml):

<bean id="childContext1" class="com.test1.child.ChildContext1"></bean>

 

[轉]Spring IOC父子容器簡介

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.