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

后端 未结 3 741
一生所求
一生所求 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:58

    Another approach using @Autowired and @Component is to use this pattern:

    @Component
    class A {
        private B b;
    
        public B getB() {
            return b;
        }
    
        public void setB(final B b) {
            this.b = b;
        }
    }
    
    
    @Component
    class B {
        private final A a;
    
        @Autowired
        public B(final A a) {
            this.a = a;
            a.setB(this);
        }
    
        public A getA() {
            return a;
        }
    }
    

    This eliminates the need for a separate @Configuration-class. Furthermore, the setB-method can possibly be package-protected if the classes exist in the same package to minimize scoping as much as possible.

提交回复
热议问题