获取命令行参数作为@Scheduled spring-boot的春季批处理作业参数



下面是我的spring-boot主类,其中有@Scheduledbeans

@EnableScheduling
@EnableBatchProcessing
@SpringBootApplication(scanBasePackages = { "com.mypackage" })
public class MyMain {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job job;

public static void main(String[] args) throws Exception {
SpringApplication.run(MyMain.class, args);
}

@Scheduled(cron = "0 00 05 * * ?")
private void perform() throws Exception {
jobLauncher.run(job, new JobParameters());
}
}

我将从命令行接收参数,我需要将其作为作业参数。我如何才能实现与@Scheduled相同的注释方法不接受任何参数。

您可以注入ApplicationArguments类型的bean,并使用它来获取应用程序参数:

@EnableScheduling
@EnableBatchProcessing
@SpringBootApplication
public class MyMain {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job job;
@Autowired
private ApplicationArguments applicationArguments;

public static void main(String[] args) throws Exception {
SpringApplication.run(MyMain.class, args);
}
@Scheduled(cron = "0 00 05 * * ?")
private void perform() throws Exception {
String[] sourceArgs = applicationArguments.getSourceArgs();
JobParameters jobParameters; // create job parameters from sourceArgs
jobLauncher.run(job, jobParameters);
}
}

您可以在访问应用程序参数部分中找到有关ApplicationArguments类型的更多详细信息。

希望这能有所帮助。

最新更新