Spring:嵌套应用上下文

4

我有一个应用上下文的层次结构。在父上下文中定义的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个回答

10

你不能这样做。父上下文无法引用子上下文中的bean定义,只能反过来使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接