Spring. Resolve circular dependency with java config and without @Autowired

后端 未结 3 755
一生所求
一生所求 2021-02-13 12:25

I\'ve got circular dependency and java config. While resolving it with xml config is very easy I can\'t resolve it with java config without @Autowired. Beans:

pu         


        
3条回答
  •  故里飘歌
    2021-02-13 12:32

    The behavior you want to get is the following

    A a = new A();
    B b = new B();
    a.setB(b);
    b.setA(a);
    

    @Bean methods don't give you that. They run to completion to provide a bean instance.

    You basically have to partially create one of the instances, then finish initializing it when you've created the other.

    @Configuration
    class Config {
        @Bean
        public A a() {
            A a = new A();
            return a;
        }
    
        @Bean
        public B b() {
            B b = new B();
            A a = a();
            b.setA(a);
            a.setB(b);
            return b;
        }
    }
    

    or

    @Bean
    public B b(A a) {
        B b = new B();
        b.setA(a);
        a.setB(b);
        return b;
    }
    

提交回复
热议问题