java - 自动装配多个 SimpleJobLauncher
问题描述
我有一个类,我想从异步运行作业。为此,我有以下代码:
@Resource
private SimpleJobLauncher jobLauncher;
@PostConstruct
public void initLauncher(){
jobLauncher.setTaskExecutor(taskExecutor());
}
但是,有一种情况我需要同步执行此操作。所以,我所做的是添加了以下变量:
@Resource
private SimpleJobLauncher synchronousJobLauncher;
我希望它不会taskExecutor
让它同步。然后我将它传递synchronousJobLauncher
给我想要同步做事的地方。但是,使用synchronousJobLauncher
给我与使用异步错误时相同的错误,这使我相信您不能像我尝试做的那样两次自动连接相同的变量。如果我不做这@PostConstruct
部分代码,同步部分会像我期望的那样工作,但异步部分不会,即使他们使用我认为是不同的作业启动器。
有任何想法吗?我尝试使用@Resource
注释而不是@Autowired
.
解决方案
我没有使用过 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.
}
}
希望这可以帮助。我知道这不是您直接要求的,但也许这个解决方案可以解决您的问题。
推荐阅读
- php - Mailchimp 基于标签的不同选择
- kubernetes - 是否可以使用 api 在 kubernetes 中编辑配置映射?
- python-3.x - 如果类型提示通知函数的可接受类型,我是否仍应引发异常?
- jquery - 如何使用字体真棒图标而不是jquery中的文本进行切换
- javascript - ASP.NET 将模型数据传递给 site.js
- excel - Excel 到 Word 到 PDF 使用 VBA
- angular - 在自定义结构指令中获取未定义的模板引用(ng-template)
- database - 用于可搜索性的键值数据库建模
- python - 熊猫:如何将应用与一系列列表一起使用
- typescript - 如何修复具有多个功能的接口的“没有重载匹配此调用”