`
weiqingfei
  • 浏览: 311812 次
  • 性别: Icon_minigender_1
  • 来自: 黑洞
社区版块
存档分类
最新评论

Spring batch的自动运行

    博客分类:
  • Java
阅读更多

一个最简单的spring batch的程序,照办官网的sample,如下

一个配置程序

 

@Configuration
@EnableBatchProcessing
@EnableAutoConfiguration
public class BatchConfiguration {

  @Autowired
  private JobBuilderFactory jobBuilderFactory;

  @Autowired
  private StepBuilderFactory stepBuilderFactory;

  @Bean
  public Step step1() {
    return stepBuilderFactory.get("step1")
        .tasklet(new Tasklet() {
          public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
            return null;
          }
        })
        .build();
  }

  @Bean
  public Job job(Step step1) throws Exception {
    return jobBuilderFactory.get("job1")
        .incrementer(new RunIdIncrementer())
        .start(step1)
        .build();
  }
}

 

 

 一个主程序

 

public class Main {
  public static void main(String [] args) {
    System.exit(SpringApplication.exit(SpringApplication.run(
        BatchConfiguration.class, args)));
  }
}

 你肯定会好奇,为啥Job就执行了呢?没看到调用啊

 

实际上在Spring batch的配置程序org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration里有以下代码

 

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled", havingValue = "true", matchIfMissing = true)
	public JobLauncherCommandLineRunner jobLauncherCommandLineRunner(
			JobLauncher jobLauncher, JobExplorer jobExplorer) {
		JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner(
				jobLauncher, jobExplorer);
		String jobNames = this.properties.getJob().getNames();
		if (StringUtils.hasText(jobNames)) {
			runner.setJobNames(jobNames);
		}
		return runner;
	}

 

 

也就是当配置文件里定义spring.batch.job.enabled为true,或者没定义(默认为true)的时候,会初始化一个JobLauncherCommandLineRunner的bean。

而在SpringApplication里有以下代码

 

	private void callRunners(ApplicationContext context, ApplicationArguments args) {
		List<Object> runners = new ArrayList<Object>();
		runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
		runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
		AnnotationAwareOrderComparator.sort(runners);
		for (Object runner : new LinkedHashSet<Object>(runners)) {
			if (runner instanceof ApplicationRunner) {
				callRunner((ApplicationRunner) runner, args);
			}
			if (runner instanceof CommandLineRunner) {
				callRunner((CommandLineRunner) runner, args);
			}
		}
	}

 也就是只要能找到ApplicationRunner或者CommandLineRunner的子类,就挨个执行。

 

默认是没有ApplicationRunner的子类的,而CommandLineRunner得子类就是JobLauncherCommandLineRunner了,所以会执行所配置的job。

如果想自己执行job的话,使用以下代码便可。

 

	@Autowired
	private JobLauncher jobLauncher;
	@Autowired
	private Job job;
	
	@Scheduled(initialDelay=3000,fixedRate = 1000)
	public void run(){
		try {
			JobExecution execution = jobLauncher.run(job, new JobParameters());
			System.out.println("Execution status: "+ execution.getStatus());
		} catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
				| JobParametersInvalidException e) {
			e.printStackTrace();
		} 
	}

 这时候,你可能会好奇,JobLauncher是哪儿配置的?

 

上面的配置文件里使用了注解@EnableBatchProcessing

这个注解会初始化以下所有bean

 

写道

 

JobRepository bean 名称 "jobRepository"
JobLauncher bean名称"jobLauncher"
JobRegistry bean名称"jobRegistry"
PlatformTransactionManager bean名称 "transactionManager"
JobBuilderFactory bean名称"jobBuilders"
StepBuilderFactory bean名称"stepBuilders"

 在程序org.springframework.batch.core.configuration.annotation.BatchConfigurationSelector会根据定义选择配置程序,默认用的是SimpleBatchConfiguration

 

public class BatchConfigurationSelector implements ImportSelector {

	@Override
	public String[] selectImports(AnnotationMetadata importingClassMetadata) {
		Class<?> annotationType = EnableBatchProcessing.class;
		AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(
				annotationType.getName(), false));
		Assert.notNull(attributes, String.format("@%s is not present on importing class '%s' as expected",
				annotationType.getSimpleName(), importingClassMetadata.getClassName()));

		String[] imports;
		if (attributes.containsKey("modular") && attributes.getBoolean("modular")) {
			imports = new String[] { ModularBatchConfiguration.class.getName() };
		}
		else {
			imports = new String[] { SimpleBatchConfiguration.class.getName() };
		}

		return imports;
	}

}

 

分享到:
评论
1 楼 zsf513 2017-09-22  
怒赞       

相关推荐

    springbatch_嵌入式jetty_动态控制的quartz

    支持web接口的批处理框架 ...springmvc4.0.7 springbatch3.0.7 quartz2.2.3 mysql5.6 oracle11g junit4.11 log4j1.2.17 mybatis3.4.1 druid1.0.17 smg3(决策引擎) jetty8.1.5 fastjson1.2.7 springjdbc3.2.14

    java毕业设计 基于SpringBoot和SpringBatch的批处理系统源码+使用文档+全部资料(优秀项目).zip

    java毕业设计 基于SpringBoot和SpringBatch的批处理系统源码+使用文档+全部资料(优秀项目).zipjava毕业设计 基于SpringBoot和SpringBatch的批处理系统源码+使用文档+全部资料(优秀项目).zip 【备注】 1、该项目...

    spring-boot-starter-batch-web

    项目batch-web-spring-boot-starter是Spring Batch的Spring Boot启动器,除了编写作业外,它负责所有工作。 请参阅文档以获取详细信息,示例和操作详细信息。 功能包括: 启动Web应用程序并自动将批处理作业部署...

    spring-batch-job-hazelcast

    使用Spring Boot创建的简单PoC项目,具有Maven 3,Spring Batch和配置为作为独立实例或群集运行的Hazelcast服务器,并在新实例启动(或关闭)时自动更改连接端口。 用法 下载仓库 与mvn package一起mvn package 并...

    spring_batch

    运行java -jar target/springBatch-1-jar-with-dependencies.jar 。笔记该程序从src / main / resources / scores.txt中读取输入文件。 并且它会自动创建表(如果没有的话),并将数据写入其中。 测试

    Bauta:Bauta是基于Spring Batch和Spring Boot的批处理自动化框架。 它添加了一个用户界面,您可以在其中启动停止重新启动作业,监视步进作业状态。 还提供了一些作业和步骤的附加组件,例如报告日志生成,作业参数处理等

    Spring Batch入​​门的便捷方法 通过基于Web的用户界面启动/停止/重新启动作业 观察工作/步骤进度和状态。 步骤可以生成可以在UI中显示的输出。 通常是报告,脚本日志,堆栈跟踪等。 提供针对不同使用场景的...

    Spring攻略(第二版 中文高清版).part1

    11.10 运行单元和集成测试 466 11.10.1 问题 466 11.10.2 解决方案 467 11.10.3 工作原理 467 11.11 使用自定义布局和模板 472 11.11.1 问题 472 11.11.2 解决方案 472 11.11.3 工作原理 472 11.12...

    Spring攻略(第二版 中文高清版).part2

    11.10 运行单元和集成测试 466 11.10.1 问题 466 11.10.2 解决方案 467 11.10.3 工作原理 467 11.11 使用自定义布局和模板 472 11.11.1 问题 472 11.11.2 解决方案 472 11.11.3 工作原理 472 11.12...

    JavaEE开发的颠覆者SpringBoot实战[完整版].part3

    7.3.1 Spring Boot 提供的自动配置 182 7.3.2 接管Spring Boot 的Web 配置 185 7.3.3 注册Servlet、Filter、Listener 186 7.4 Tomcat 配置 187 7.4.1 配置Tomcat 187 7.4.2 代码配置Tomcat 188 7.4.3 替换Tomcat 190...

    JavaEE开发的颠覆者SpringBoot实战[完整版].part2

    7.3.1 Spring Boot 提供的自动配置 182 7.3.2 接管Spring Boot 的Web 配置 185 7.3.3 注册Servlet、Filter、Listener 186 7.4 Tomcat 配置 187 7.4.1 配置Tomcat 187 7.4.2 代码配置Tomcat 188 7.4.3 替换Tomcat 190...

    JavaEE开发的颠覆者SpringBoot实战[完整版].part1

    7.3.1 Spring Boot 提供的自动配置 182 7.3.2 接管Spring Boot 的Web 配置 185 7.3.3 注册Servlet、Filter、Listener 186 7.4 Tomcat 配置 187 7.4.1 配置Tomcat 187 7.4.2 代码配置Tomcat 188 7.4.3 替换Tomcat 190...

    springboot学习思维笔记.xmind

    Spring Batch Spring Security Spring HATEOAS Spring Social Spring AMQP Spring Mobile Spring for Android Spring Web Flow Spring Web Services Spring LDAP...

    springboot参考指南

    1. 介紹 2. I.... 在启动时执行Spring Batch作业 ix. 70. 执行器(Actuator) i. 70.1. 改变HTTP端口或执行器端点的地址 ii. 70.2. 自定义'白标'(whitelabel,可以了解下相关理念)错误页面 x. 71...

    paig:纸作为逆图形的代码

    逆向物理学 此存储库包含论文Physics-as-Inverse-Graphics:视频的无监督物理参数估计( )的代码。 进行实验 训练跑步: ...在训练结束时,这将自动在测试集上运行(带有外推范围的评估)。 要仅对先前

    JdbcTemplateTool.zip

    运行测试用例,等待绿色条。然后去数据库会看到多了一条记录 :idnamejoin_dateage4billy2014-09-24 22:51:2033高级教程  以下是各个方法的详细介绍list把查询结果转换为PO列表,不需要调用BeanPropertyRowMapper...

    支持多数据库的ORM框架ef-orm.zip

    同时每个查询都可以针对batch、fetchSize、maxResult、缓存、级联操作类型等进行调整和开关,可以将性能调到最优。可在主流数据库之间任意切换 支持Oracle、MySQL、Postgres、MSSQL、GBase、SQLite、HSQL、Derby等...

Global site tag (gtag.js) - Google Analytics