代码之家  ›  专栏  ›  技术社区  ›  Itay Maman

Spring:嵌套应用程序上下文

  •  4
  • Itay Maman  · 技术社区  · 17 年前

      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);
         }
      }
    

      <?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 回复  |  直到 17 年前
        1
  •  10
  •   skaffman    17 年前

    你不能那样做。父上下文不能引用子上下文中的bean定义。它只会反过来起作用。

    推荐文章