Spring: Nested Application Contexts

I have a hierarchy of application contexts. The bean that is defined in the parent context depends on the bean that is defined in the child. Here's what it looks like:

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

The xml file that defines the "a" bean is as follows:

  <?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>

The problem is that B is not entered in A. Injection will only happen if I register the single “b” with the parent, which is not an option in my program.

Any ideas?

+3
source share
1 answer

You cannot do this. Parent contexts cannot reference bean definitions in child contexts. It only works the other way around.

+10

Source: https://habr.com/ru/post/1712039/


All Articles