繁体   English   中英

如何在 Spring Boot 中运行自动装配线程

[英]How to run autowired thread in spring boot

我正在努力在 Spring Boot 中使用自动装配的 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 中创建这个线程之前,我会得到注释行中提到的错误。 所以我切换到taskexecutor。 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()
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM