本文介绍了春天.使用Java配置解决循环依赖,不使用@Autowired的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有循环依赖项和Java配置.尽管使用xml config解决它非常容易,但是如果没有@Autowired,我就无法使用java config来解决它.豆类:

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:

public class A {
    private B b;

    public B getB() {
        return b;
    }

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

public class B {
    private A a;

    public A getA() {
        return a;
    }

    public void setA(A a) {
        this.a = a;
    }
}

我已经尝试过了(我已经阅读了@Bean注释,Spring不会在每次引用bean时都调用方法,但是在这种情况下,实际上它一直在被调用):

I've tried this(I've read that with @Bean annotation Spring won't invoke method every time bean is referenced, but in this case it's actually been invoked all the time):

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

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

这是配置类字段的@Autowired:

And this, with @Autowired of Configuration class fields:

@Configuration
public class Config {
    @Autowired
    A a;
    @Autowired
    B b;

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

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

我还尝试了@Lazy注释.无济于事.但是如果我用@Autowired注释A和B的设置者,效果很好.但这不是我现在想要的.我在做什么错,有没有办法解决Java配置中的循环依赖,而无需使用@Autowired?

Also I've tried all above with @Lazy annotation. Doesn't help. But works perfectly if I annotate setters of A and B with @Autowired. But it's not what I want right now. What am I doing wrong and is there any way to resolve Circular dependency in java config without usage of @Autowired?

推荐答案

您想要获得的行为如下

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

@Bean 方法无法满足您的要求.他们运行完成以提供一个bean实例.

@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;
    }
}

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

这篇关于春天.使用Java配置解决循环依赖,不使用@Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 22:58