首页 > 解决方案 > 自动装配多个 SimpleJobLauncher

问题描述

我有一个类,我想从异步运行作业。为此,我有以下代码:

@Resource
private SimpleJobLauncher jobLauncher;

@PostConstruct
public void initLauncher(){
    jobLauncher.setTaskExecutor(taskExecutor());
}

但是,有一种情况我需要同步执行此操作。所以,我所做的是添加了以下变量:

@Resource
private SimpleJobLauncher synchronousJobLauncher;

我希望它不会taskExecutor让它同步。然后我将它传递synchronousJobLauncher给我想要同步做事的地方。但是,使用synchronousJobLauncher给我与使用异步错误时相同的错误,这使我相信您不能像我尝试做的那样两次自动连接相同的变量。如果我不做这@PostConstruct部分代码,同步部分会像我期望的那样工作,但异步部分不会,即使他们使用我认为是不同的作业启动器。

有任何想法吗?我尝试使用@Resource注释而不是@Autowired.

标签: javaspringspring-batch

解决方案


我没有使用过 SimpleJobLaunchers,但通常在 Spring 中我总是使用@Async注解,这使得异步执行变得非常简单。您所要做的就是@EnableAsync在任何配置文件中添加此注释,就像下面的一样。

@Configuration
@EnableAsync
public class MvcConfig extends WebMvcConfigurerAdapter { ... }

现在,所有关于添加@Async到任何将异步运行的方法。

@Component
class AsyncTask {

     @Async
     public Future<String> run() throws InterruptedException {
        return new AsyncResult<String>("return value");
     }
}

如果您想等待结果,您可以执行以下操作。

public void callAsyncTask() {
    try {
        Future<String> future =  asyncTask.run();
        // Do some other things while the async task is running.
        // future.get() will block the function and wait for the result.
        String asyncResult = future.get();
    } catch(InterruptedException e) {
        e.printStackTrace();
        // Do something else.
    }
}

希望这可以帮助。我知道这不是您直接要求的,但也许这个解决方案可以解决您的问题。


推荐阅读