java - 如何在 Spring Boot 中运行自动装配线程
问题描述
我正在努力在 Spring Boot 中使用 autowired bean 在后台运行线程。从所有互联网资源中,我发现如果我创建对象的新实例,它将抛出 null,因为它不是 spring 生命周期的一部分,我需要使用 executorTask 并将其作为 bean 注入。这是我到目前为止没有运气的尝试。
我的 Application.java 文件
@SpringBootApplication
@EnableAsync
public class Application {
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
SpringApplication.run(Application.class, args);
}
}
我的 ThreadConfig.java 文件 [我实际上在其中为任务执行器创建 bean]
@Configuration
public class ThreadConfig {
@Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(4);
executor.setThreadNamePrefix("default_task_executor_thread");
executor.initialize();
return executor;
}
}
AsyncService.java 文件
@Service
public class AsynchronousService {
@Autowired
private ApplicationContext applicationContext;
@Autowired
private TaskExecutor taskExecutor;
public void executeAsynchronously() {
NotificationThread myThread = applicationContext.getBean(NotificationThread.class);
taskExecutor.execute(myThread);
}
}
我想在后台运行的实际线程
@Component
@Scope("prototype")
public class NotificationThread implements Runnable {
@Autowired
private UserDao userDao;
public void run() {
while (true) {
System.out.println("thread is running...");
List<User> users = userDao.findAllByType("1"); //Used to get Error here when running directly from main
try {
Thread.sleep(1000 );
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
在我直接在 main 中创建此线程之前,我会收到注释行中提到的错误。所以我切换到任务执行器。NotificationThread 是我想在后台运行的线程。但它不起作用,不确定要进行哪些更改。会帮助指导。
解决方案
需要调用服务方法executeAsynchronously()
来启动流程。
您可以按如下方式自动连接AsynchronousService
并ThreadAppRunner
调用service.executeAsynchronously()
。
@Component
public class ThreadAppRunner implements ApplicationRunner {
@Autowired
AsynchronousService service;
@Override
public void run(ApplicationArguments args) throws Exception {
service.executeAsynchronously()
}
}
推荐阅读
- rabbitmq - 带有 MQTT 的 RabbitMQ 在连接时发送消息
- sql - Postgresql:一行中多行的值
- android-studio - 无法使用导入包中的成员 (Flutter)
- python - python selenium phantomjs 执行脚本
- ansible - 在 Ansible Tower 上获取部署次数
- c# - 仅将 DataGridView 单元格边框样式设置为选定列
- r - 带有希伯来语标签的ggplot
- vba - VB 和 VBA 程序设置在 RegEdit 中不可见,但可通过 VBA 访问
- ruby - 提供响应后立即从 `call(env)` 返回
- javascript - Javascript代码在我的项目中不起作用