gpt4 book ai didi

java - 如何使用参数在for循环中注入(inject)bean

转载 作者:行者123 更新时间:2023-12-02 01:08:13 24 4
gpt4 key购买 nike

我可以在 for 循环中注入(inject)带参数的 Bean 吗?我不想在以下示例中手动初始化 TheService:

@Singelton
public class Scheduler {
@Inject
private UserQueryService userQueryService;

@Schedule(hour = "*", minute = "*", second = "*/30", persistent = false)
public void execute() {
final List<User> users = userQueryService.findAll();
for (final User user : users) {
final TheService service = new TheService(user.getName(), user.getAge());
service.doSomething();
}
}
}

例如,运行时是否可以将值从 for 循环注入(inject)到生产者的方法并使用 CDI 注入(inject)服务?我知道,字符串和原始值不能被注入(inject),但也许你可以帮助我并提出一些解决方案。

@ApplicationScoped
public class TheServiceFactory {
@Produces
@RequestScoped
public TheService createTheService(final String name, final int age) {
...
}
}

更新:TheService 还有其他带有 @Inject 注释的字段。

最佳答案

我明白你想做什么。

在任何给定时刻,您都希望获取系统中所有用户的快照。然后,对于每个服务,您都希望存在一个 RequestScoped TheService,然后用它来执行某些操作。

正如所写,这对于 CDI 来说实际上是不可能的。

我假设您想要生成一个 TheService 实例并使用 CDI 的依赖机制,因为 TheService 有一些 @Inject 带注释的字段?我只是猜测。

如果是这样,你可以像这样伪造它:

final Unmanaged<TheService> unmanagedService = new Unmanaged<TheService>(TheService.class);
final UnmanagedInstance<TheService> serviceInstance = unmanagedService.newInstance();
final TheService service = serviceInstance.produce().inject().postConstruct().get();
// Any @Inject-annotated fields in service will now be "filled" if possible; that's
// what the inject() call above does; any @PostConstruct methods it has will have been
// invoked, etc.
// You'll have to manually set its user and age properties:
service.setUser(user.getName());
service.setAge(user.getAge());
service.doSomething();
// The TheService instance is NOT in request scope; *you* are fully in control
// of its lifecycle, so don't forget to dispose it when you're done. You may
// need to put this in a finally block to ensure it happens:
serviceInstance.preDestroy().dispose();

CDI bean 在设计上是“静态”的。您想要做的是动态的,即它在运行时发生变化(也许查询服务每次调用时都会返回完全不同的 User 实例)。因此,注入(inject)完全托管的 TheService 并不是您真正想要做的,因为您无法预测其中会有多少个或它们将如何构建。

CDI 中的非托管 构造适用于您想要自己管理本来属于 CDI bean 的事物的生命周期

我希望这会有所帮助。

关于java - 如何使用参数在for循环中注入(inject)bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59743004/

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