簡體   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