gpt4 book ai didi

java - Spring Boot 中的分层 Bean 依赖

转载 作者:行者123 更新时间:2023-12-02 11:38:57 24 4
gpt4 key购买 nike

我有一个与父类 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com