Spring:嵌套的应用程序上下文

时间:2009-07-07 19:41:45

标签: java spring dependency-injection

我有一个应用程序上下文的层次结构。父上下文中定义的bean依赖于子中定义的bean。这是它的样子:

  public class X {

     public static class A {
        public B b;
        public void setB(B b) { this.b = b; }
     }

     public static class B { }

     public static void main(String[] args) {
        ClassPathXmlApplicationContext parent = new ClassPathXmlApplicationContext(
           "/a.xml");
        go1(parent);
     }

     public static void go1(ClassPathXmlApplicationContext parent) {
        GenericApplicationContext child = new GenericApplicationContext(parent);

        child.getBeanFactory().registerSingleton("b", new B());

        A a = (A) child.getBean("a");
        Assert.assertNotNull(a.b);
     }
  }

定义“a”bean的xml文件如下所示:

  <?xml version="1.0" encoding="UTF-8"?>

  <beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="a" class="X$A" autowire="byName" lazy-init="true"/>


  </beans>

问题是B没有注入A.只有当我用父母注册“b”单例时才会发生注入 - 这在我的程序中不是一个选项。

有什么想法吗?

1 个答案:

答案 0 :(得分:10)

你做不到。父上下文不能引用子上下文中的bean定义。它只是相反的方式。

相关问题