How to pass parameters from spring boot to spring batch

I search a solution to how passing springboot parameters to my spring batch job and then get the value of parameter in my writer. when I load the key in my writer is still null. Somebody can help me please ?

    @GetMapping("/load/{id}")
    public BatchStatus load (@PathVariable String id) throws 
    JobExecutionException {
    JobParameters jobParameters = new JobParametersBuilder()
                .addLong("time", System.currentTimeMillis())
                .addString("key", id).toJobParameters();

        JobExecution jobExecution = jobLauncher.run(job, jobParameters);

        return jobExecution.getStatus();
    }

Here is my Batch code configuration

@Configuration
@EnableBatchProcessing
public class BatchConfig {

    @Value("${path.to.react.file}")
    private Resource resource;

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    UserDao userDao;

    @Value("#{jobParameters['key']}")
    private String pathToFile;

    @Bean
    public Job job() {
        return jobBuilderFactory.get("readCSVFilesJob")
                .incrementer(new RunIdIncrementer())
                .start(step())
                .build();
    }

    @Bean
    public Step step() {
        return stepBuilderFactory.get("step1").<UserDTO, 
    UserDTO>chunk(100)
                .reader(Reader.reader(resource))
                .processor(new Processor())
                .writer(new Writer(userDao))
                .build();
       }
   }

And my Writer

@StepScope
public class Writer implements ItemWriter<UserDTO> {


private  UserDao userDao;

@Value("#{jobParameters['key']}")
private String key;

public Writer(UserDao userDao) {
    this.userDao = userDao;

}

@Override
public void write(List<? extends UserDTO> items) throws Exception {
    userDao.writePnoFile(items);
}

}


Solution 1:

Add @Scope("step") to your writer and then inject parameters via @Value annotation:

@Value("#{jobParameters['key']}")
String key;