【问题标题】:How to run autowired thread in spring boot如何在 Spring Boot 中运行自动装配线程
【发布时间】:2020-02-08 02:07:32
【问题描述】:

我正在努力在 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 是我想在后台运行的线程。但它不起作用,不确定要进行哪些更改。会帮助指导。

【问题讨论】:

  • Spring 提供@Scheduled 自动为您执行此操作。

标签: java spring multithreading spring-boot


【解决方案1】:

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

您可以按如下方式将AsynchronousService 自动连接到ThreadAppRunner 并致电service.executeAsynchronously()

@Component
public class ThreadAppRunner implements ApplicationRunner {

    @Autowired
    AsynchronousService service;

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

}

【讨论】:

  • ApplicationRunner 是否负责调用它,还是我需要在 main 中创建一个 ThreadAppRunner 实例?
  • 当您实现ApplicationRunner 并使用@Component 对其进行注释时,它将在应用程序启动时自动运行。更新答案并修改代码添加注解
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-09
  • 1970-01-01
  • 2017-09-07
  • 1970-01-01
  • 2019-10-21
  • 2018-07-28
相关资源
最近更新 更多