java - 在 Spring Boot 的后台运行线程并能够自动装配
问题描述
我正在尝试构建一个 Spring Boot 应用程序,它将在后台运行一个长时间运行的线程,但我遇到的问题是我无法在线程中自动装配 spring bean(至少我这样做的方式)
我创建了一个显示我面临的问题的存储库
https://github.com/NikosDim/spring-boot-background-thread
在作为我的线程的 BackgroundThread 类中,我希望能够自动装配对象(查找 //TODO)
谢谢
缺口
解决方案
你应该制作BackgroundThread
一个原型bean:
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public BackgroundThread backgroundThreadBean(Dep1 dep1) {
return new BackgroundThread(dep1);
}
然后BackgroundThread
注入BackgroundThreadManager
:
@Autowired
private BackgroundThread thread;
如果需要BackgroundThread
动态创建多个实例那么ObjectFactory
可以使用。将工厂注入BackgroundThreadManager
:
@Autowired
private ObjectFactory<BackgroundThread> backgroundThreadObjectFactory;
并调用ObjectFactory.getObject
方法来创建BackgroundThread
.
有关原型范围的更多信息,请参见此处。
推荐阅读
- postgresql - JPA - 非主键的双重关系和外键
- javascript - 如何通过使用 jQuery 添加系统工作来完成这个测验?
- javascript - 根据其他选择更改动态添加的下拉菜单上的选项
- c# - 为什么 UTF-7 解释变音符号正确而 UTF-8 不正确?
- javascript - 通过 PHP Post 将 Javascript 变量传递到另一个页面
- sql - 在sql中查找列值组合的不同计数
- javascript - 正则表达式将日期附加到具有文件扩展名和没有文件扩展名的字符串
- c++ - Boost ASIO - 如何在 TCP 消息前面附加标头
- r - 基于查找表使用 dplyr 重新编码矩阵值
- android - 新创建的服务的 AndroidP-SELinux 权限被拒绝