首页 > 解决方案 > 如何在 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 是我想在后台运行的线程。但它不起作用,不确定要进行哪些更改。会帮助指导。

标签: javaspringmultithreadingspring-boot

解决方案


需要调用服务方法executeAsynchronously()来启动流程。

您可以按如下方式自动连接AsynchronousServiceThreadAppRunner调用service.executeAsynchronously()

@Component
public class ThreadAppRunner implements ApplicationRunner {

    @Autowired
    AsynchronousService service;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        service.executeAsynchronously()
    }

}

推荐阅读