gpt4 book ai didi

java - 如何在 Spring 中以编程方式生成新的托管 bean

转载 作者:行者123 更新时间:2023-12-03 20:25:04 25 4
gpt4 key购买 nike

这个例子只是一个虚拟的例子来展示我遇到的问题,所以不要太着迷于用替代方法来解决这里的具体问题。我的问题更多是关于理解在 Spring 中解决一类问题的正确技术

假设我有一个托管 bean Info

@Component
public class Info {
private final String activeProfile;
private final Instant timestamp;

public Info(@Value("${spring.profiles.active}") String activeProfile) {
this.activeProfile = activeProfile;
this.timestamp = Instant.now();
}
}

这里的关键是 bean 需要 Spring 注入(inject)的东西(我的示例中的 Activity 配置文件)以及每次创建 bean 时都会更改的东西(我的示例中的时间戳)。由于后者,我不能使用 Singleton范围。获取此类 bean 的新实例的正确方法是什么?

我目前拥有的是,bean 不是托管的(没有 @Component ,没有 @Value ),我有一个托管服务( Controller )调用常规的构造函数 Info POJO 显式。就像是
@RestController
public class InfoRestController {
@GetMapping
public Info getInfo(@Value("${spring.profiles.active}") String activeProfile) {
return new Info(activeProfile);
}
}

该解决方案的问题在于,它会将 Activity 配置文件的知识泄露给 Controller ,只是为了将其传递给 Info 的构造函数。 ,从概念上讲, Controller 不应该知道构造 Info bean。这是依赖注入(inject)的要点之一

我想到了一些潜在的解决方案:
  • 引用 InfoFactory FactoryBean在 Controller 中,然后 return factory.getObject(); .但是我真的需要为这样一个简单的案例创建一个新类吗?
  • 有一个@Bean构造托管 bean 的工厂方法。这仍然存在该方法正在实例化 Info 的问题。 POJO 显式,因此它本身需要对其进行 Spring 注入(inject)。此外,这是完整的样板文件。

  • build Info bean 是如此微不足道,以至于我想在 Spring 中有一种更简单的方法可以实现这一点。有没有?

    最佳答案

    缺少的一 block 拼图是javax.inject.Provider .我不知道它,但它具有我正在寻找的界面。最终的解决方案是让 Spring 管理 bean ( Info ) 并使用 Provider在休息 Controller 中。这是 bean,几乎和 OP 中的一样

    @Component
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public class Info {
    private final String activeProfile;
    private final Instant timestamp;

    public Info(@Value("${spring.profiles.active}") String activeProfile) {
    this.activeProfile = activeProfile;
    this.timestamp = Instant.now();
    }
    }

    bean 具有 ruhul 建议的 Prototype 范围。我之前尝试过,但没有 Provider我还是被困住了。这是如何在 Controller 中返回它
    @RestController
    public class InfoRestController {
    @Autowire
    private Provider<Info> infoProvider;

    @GetMapping
    public Info getInfo() {
    return infoProvider.get();
    }
    }

    为了完整起见,我找到了另一种更丑陋的方法,即注入(inject) Spring ApplicationContext然后使用 context.getBean("info")但是对 spring 上下文和字符串名称的依赖是一种气味。 Provider 的解决方案更加专注

    关于java - 如何在 Spring 中以编程方式生成新的托管 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58629459/

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