在同一项目中,我有两个独立的Spring Batch作业,因为我想使用相同的与基础架构相关的bean。一切都用Java配置。我想知道是否存在适当的方法来独立启动作业,例如,例如基于main方法中的第一个Java应用程序自变量。如果我运行,SpringApplication.run那么第二个工作就会被魔术执行。主要方法如下:
SpringApplication.run
@ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication app = new SpringApplication(Application.class); app.setWebEnvironment(false); ApplicationContext ctx= app.run(args); } }
然后按照Spring.io上的“ Spring Batch入门”教程中的介绍配置两个作业。这是第一个作业的配置文件,第二个以相同的方式配置。
@Configuration @EnableBatchProcessing @Import({StandaloneInfrastructureConfiguration.class, ServicesConfiguration.class}) public class AddPodcastJobConfiguration { @Autowired private JobBuilderFactory jobs; @Autowired private StepBuilderFactory stepBuilderFactory; //reader, writer, processor... }
为了启用模块化,我创建了一个AppConfig类,在其中定义了两个作业的工厂:
@Configuration @EnableBatchProcessing(modular=true) public class AppConfig { @Bean public ApplicationContextFactory addNewPodcastJobs(){ return new GenericApplicationContextFactory(AddPodcastJobConfiguration.class); } @Bean public ApplicationContextFactory newEpisodesNotificationJobs(){ return new GenericApplicationContextFactory(NotifySubscribersJobConfiguration.class); } }
PS我是Java配置Spring Boot和Spring Batch中的Spring配置新手…
要从main方法运行所需的作业,可以从应用程序上下文中加载所需的作业配置bean和JobLauncher,然后运行它:
@ComponentScan @EnableAutoConfiguration public class ApplicationWithJobLauncher { public static void main(String[] args) throws BeansException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException, InterruptedException { Log log = LogFactory.getLog(ApplicationWithJobLauncher.class); SpringApplication app = new SpringApplication(ApplicationWithJobLauncher.class); app.setWebEnvironment(false); ConfigurableApplicationContext ctx= app.run(args); JobLauncher jobLauncher = ctx.getBean(JobLauncher.class); JobParameters jobParameters = new JobParametersBuilder() .addDate("date", new Date()) .toJobParameters(); if("1".equals(args[0])){ //addNewPodcastJob Job addNewPodcastJob = ctx.getBean("addNewPodcastJob", Job.class); JobExecution jobExecution = jobLauncher.run(addNewPodcastJob, jobParameters); } else { jobLauncher.run(ctx.getBean("newEpisodesNotificationJob", Job.class), jobParameters); } System.exit(0); } }
令我感到困惑的是,第二个作业被执行了,即使第一个作业似乎被跑步者“捡起了”……问题是,在两个作业的配置文件中,我都使用了标准方法名称writer(), reader(), processor() and step(),使用了第二个作业中的那些似乎没有任何警告就“覆盖”了第一个作业中的那些…我使用了带有的应用程序配置类@EnableBatchProcessing(modular=true),我认为它会被Spring Boot神奇地使用:
writer(), reader(), processor() and step()
@EnableBatchProcessing(modular=true)
准备就绪时,我将写一篇有关它的博客文章,但是在此之前,可在https://github.com/podcastpedia/podcastpedia- batch(工作/学习进行中)中找到该代码。