java - Spring Boot 中的分层 Bean 依赖

标签 java spring spring-boot dependency-injection aop

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

相关文章:

java - 在链表中添加节点

java - Spring - 将自定义实例传递给构造函数

java - 如何为 Spring Batch 应用响应式(Reactive)

java - 无法订阅 Mono<XXX> spring webflux

spring - 在 Spring Boot 应用程序中使用 Coda Hale Meter

Java/OAF 通过 Callable 语句进行日期转换错误

java - 有趣的类CastException

java - 如何为 Eclipse 指定 Java 虚拟机?

java - @Query 和存储库中的错误

java - 使用 Spring RestTemplate 向每个 REST 请求添加查询参数