Spring Batch — MethodInvokingTaskletAdapter example

Prateek
1 min readNov 29, 2021

--

In this example, we’ll make the use of MethodInvokingTaskletAdapter and call the method.

MethodInvokingTaskletAdapter — A Tasklet that wraps a method in a POJO. By default the return value is ExitStatus.COMPLETED unless the delegate POJO itself returns an ExitStatus. The POJO method is usually going to have no arguments, but a static argument or array of arguments can be used by setting the arguments property.

import org.springframework.stereotype.Service;

@Service
public class CustomerService {
public void serviceMethod(String message) {
System.out.println(String.format("Got your param %s", message));
}
}

MethodInvokingTaskletAdapter.java

@EnableBatchProcessing
@SpringBootApplication
public class MethodInvokingTaskletApplication {


@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;

@Autowired
private CustomerService customerService;

@Bean
public Job methodInvokingJob() {
return this.jobBuilderFactory.get("methodInvokingJob")
.start(this.methodInvokingStep())
.build();
}

@Bean
public Step methodInvokingStep() {
return this.stepBuilderFactory.get("methodInvokingStep")
.tasklet(this.methodInvokingTasklet(null))
.build();
}

@Bean
@StepScope
public MethodInvokingTaskletAdapter methodInvokingTasklet(@Value("#{jobParameters['message']}") String message) {
MethodInvokingTaskletAdapter methodInvokingTaskletAdapter = new MethodInvokingTaskletAdapter();
methodInvokingTaskletAdapter.setTargetObject(this.customerService);
methodInvokingTaskletAdapter.setTargetMethod("serviceMethod");
methodInvokingTaskletAdapter.setArguments(new String[]{message});
return methodInvokingTaskletAdapter;
}

public static void main(String[] args) {
SpringApplication.run(MethodInvokingTaskletApplication.class, "message=John Doe");
}
}

application.yml

spring:
datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/postgres
username: postgres
password: postgres
jpa:
hibernate:
ddl-auto: none
show-sql: true
database: postgresql
database-platform: org.hibernate.dialect.PostgreSQLDialect
open-in-view: false
generate-ddl: false

batch:
initialize-schema: always

logging:
pattern:
console: "%d %-5level %logger : %msg%n"
level:
org.springframework: INFO
org.hibernate: DEBUG

--

--

Prateek
Prateek

Written by Prateek

Java Developer and enthusiast

No responses yet