Search code examples
javaspringspring-bootdependency-injectionaop

Hierarchical Bean Dependency in Spring Boot


I have a hierarchy of beans dependency of same parent class S as:

A -> B -> C

where Bean A contains bean B, bean B contains C with code structure something like this:

public class A extends S {
    private S successor;
}

public class B extends S {
    private S successor;       
}

public class C extends S {       
    private S successor;
}

And when implementing I have

A a = new A();
B b = new B();
C c = new C();
a.successor = b;
b.successor = c;

What I really want to do here to set all the immediate above bean creation and dependency relationships in the Configuration instead of hardcoding in the code; something like:

@Configuration
public class MyConfig {


    @Bean
    public A a {
        return new A();
    }

    @Bean
    public B b {
        B b = new B();
        A a; // somehow get the bean A here
        a.successor = b;
    }

    @Bean
    public C c {
        C c = new C();
        B b; // somehow get the bean b here
        b.successor = c;
    }
}

Any inputs on how to go about this using Spring boot Dependency injection?


Solution

  • You can pass required beans as arguments to your provider methods.

    @Bean
    public A a() {
        return new A();
    }
    
    @Bean
    public B b(A a) {
        B b = new B();
        a.successor = b;
        return b;
    }
    
    @Bean
    public C c(B b) {
        C c = new C();
        b.successor = c;
        return c;
    }
    

    However, this sets the a.successor only when B is injected somewhere. I believe this is not what you expect, and inverting the construction chain is desired:

    @Bean
    public A a(B b) {
        A a = new A();
        a.successor = b;
        return a;
    }
    
    @Bean
    public B b(C c) {
        B b = new B();
        b.successor = c;
        return b;
    }
    
    @Bean
    public C c() {
        return new C();
    }