標籤: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父子容器簡介