首页 > 解决方案 > 在 Spring Boot 的后台运行线程并能够自动装配

问题描述

我正在尝试构建一个 Spring Boot 应用程序,它将在后台运行一个长时间运行的线程,但我遇到的问题是我无法在线程中自动装配 spring bean(至少我这样做的方式)

我创建了一个显示我面临的问题的存储库

https://github.com/NikosDim/spring-boot-background-thread

在作为我的线程的 BackgroundThread 类中,我希望能够自动装配对象(查找 //TODO)

谢谢

缺口

标签: javaspringspring-boot

解决方案


你应该制作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.

有关原型范围的更多信息,请参见此处


推荐阅读