基于springboot3.1.0的springbatch入门案例,并且使用作业参数增量new RunIdIncremeter()
时间: 2024-02-13 22:03:28 浏览: 156
OpenCV 3.1.0 图像处理教程基础教程培训PPT课件文档+配套示例源代码.zip
好的,下面是一个基于Spring Boot 3.1.0的Spring Batch入门案例,并且使用了作业参数增量的示例代码:
1. 首先,需要在pom.xml中添加Spring Batch和Spring Boot的依赖:
```xml
<!-- Spring Batch -->
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>4.3.3</version>
</dependency>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
```
2. 创建一个JobLauncher和JobRepository的配置类:
```java
@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private DataSource dataSource;
@Bean
public JobRepository jobRepository() throws Exception {
JobRepositoryFactoryBean factoryBean = new JobRepositoryFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setTransactionManager(new ResourcelessTransactionManager());
factoryBean.setDatabaseType("H2");
return factoryBean.getObject();
}
@Bean
public SimpleJobLauncher jobLauncher() throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository());
return jobLauncher;
}
}
```
3. 创建一个简单的Job:
```java
@Configuration
public class SimpleJobConfig {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job simpleJob() {
return jobBuilderFactory.get("simpleJob")
.incrementer(new RunIdIncrementer())
.start(step1())
.build();
}
@Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("Hello, World!");
return RepeatStatus.FINISHED;
})
.build();
}
}
```
4. 在主类中启动Job:
```java
@SpringBootApplication
@EnableBatchProcessing
public class MainApplication {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job simpleJob;
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner() {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
JobParameters jobParameters = new JobParametersBuilder()
.addLong("time", System.currentTimeMillis())
.toJobParameters();
jobLauncher.run(simpleJob, jobParameters);
}
};
}
}
```
5. 运行程序,控制台输出"Hello, World!"。
这个示例演示了如何在Spring Batch中使用作业参数增量,并创建了一个简单的Job,启动这个Job时会输出"Hello, World!"。请注意,这个示例只是一个基本的入门案例,实际使用时需要根据实际情况进行修改。
阅读全文