我有一个与父类 S 相同的 beans 依赖关系层次结构:
A -> B -> C
其中 Bean A 包含 Bean B,Bean B 包含 C,代码结构如下:
public class A extends S {
private S successor;
}
public class B extends S {
private S successor;
}
public class C extends S {
private S successor;
}
在实现时我有
A a = new A();
B b = new B();
C c = new C();
a.successor = b;
b.successor = c;
我真正想做的是在Configuration
中设置所有直接上面的bean创建和依赖关系,而不是在代码中硬编码;像这样:
@Configuration
public class MyConfig {
@Bean
public A a {
return new A();
}
@Bean
public B b {
B b = new B();
A a; // somehow get the bean A here
a.successor = b;
}
@Bean
public C c {
C c = new C();
B b; // somehow get the bean b here
b.successor = c;
}
}
关于如何使用 Spring boot 依赖注入(inject)来解决这个问题有什么建议吗?
最佳答案
您可以将所需的 bean 作为参数传递给提供程序方法。
@Bean
public A a() {
return new A();
}
@Bean
public B b(A a) {
B b = new B();
a.successor = b;
return b;
}
@Bean
public C c(B b) {
C c = new C();
b.successor = c;
return c;
}
但是,只有当 B 被注入(inject)某处时,才会设置 a.successor。我相信这不是您所期望的,并且需要反转构造链:
@Bean
public A a(B b) {
A a = new A();
a.successor = b;
return a;
}
@Bean
public B b(C c) {
B b = new B();
b.successor = c;
return b;
}
@Bean
public C c() {
return new C();
}
关于java - Spring Boot 中的分层 Bean 依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48714573/