@PostConstruct is triggered when not all cascading bean properties have been initialized in Spring

For example, I got grade A, B, C

@Service
public class A {

    private B b;

    @PostConstruct
    public void initialize() {
        b.computeUsingC();
    }

    @Autowired
    public void setB(B b) {
        this.b = b;
    }
    ...
}

@Service
public class B {

    private C c;

    public computeUsingC() {
        c.compute()
    }

    @Autowired
    public void setC(C c) {
        this.c = c;
    }
    ...
}

@Service
public class C {
    private A a
    public void compute() {
        a.otherMethod();
    }
    ...
    public void setA(A a) {
        this.a = a;
    }
}

      

I got NullpointException on line: c.compute()

when starting Spring because c is not connected yet.
I think I A

shouldn't run a method with @PostConstruct annotation before it B

is fully initialized. Although B only gets a copy for himself.

+3


source to share


1 answer


I found out that I got a circular reference for A -> B -> C -> A. So Spring cannot fully initialize B before using it.



+2


source







All Articles