Requested bean is currently in creation: Is there an unresolvable circular reference?

后端 未结 7 821
夕颜
夕颜 2020-12-08 01:48

i am using spring 3, and i have two beans of view scope:

1- Bean1:

@Component(\"bean1\")
@Scope(\"view\")
public class Bean1 {

@Aut         


        
7条回答
  •  遥遥无期
    2020-12-08 02:13

    Spring uses an special logic for resolving this kind of circular dependencies with singleton beans. But this won't apply to other scopes. There is no elegant way of breaking this circular dependency, but a clumsy option could be this one:

    @Component("bean1")
    @Scope("view")
    public class Bean1 {
    
        @Autowired
        private Bean2 bean2;
    
        @PostConstruct
        public void init() {
            bean2.setBean1(this);
        }
    }
    
    @Component("bean2")
    @Scope("view")
    public class Bean2 {
    
        private Bean1 bean1;
    
        public void setBean1(Bean1 bean1) {
            this.bean1 = bean1;
        }
    }
    

    Anyway, circular dependencies are usually a symptom of bad design. You would think again if there is some better way of defining your class dependencies.

提交回复
热议问题