-1

I am working on Spring Batch with Spring Boot.

I am trying to inject service layer in ItemWriter but it is not working.

I am getting service as null

    @Component
    public class DataWriter implements ItemWriter<String> {

        @Autowired
        PersonService service;

        @Override
        public void write(List<? extends String> messages) throws Exception {
            //personDao.getEmployee();
            System.out.println("I am in read");
            service.save();
            System.out.println("Writing the data ");
        }
    }

Service layer


    @Service
    public class PersonService {

        @Autowired 
        PersonDao dao;

        public void save() {
            System.out.println(dao);
        }
    }

configuration file

This is my configuration file.I think i am creating datawriter object by new key word and it may be problem.If it is then how i fix it.

@Configuration
public class JobConfiguration {
    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired(required = true)
    public JobLauncher JobLauncher;

    @Autowired
    Job processJob;

    @Bean
    public Job processJob() {
        return jobBuilderFactory.get("processJob").incrementer(new RunIdIncrementer()).listener(listener())
                .flow(orderStep1()).end().build();
    }

    @Bean
    public Step orderStep1() {
        return stepBuilderFactory.get("orderStep1").<String, String>chunk(1).reader(new DataReader())
                .processor(new DataProcessor()).writer(new DataWriter()).build();
    }

    @Bean
    public JobExecutionListener listener() {
        return new JobCompletionListener();
    }



    @Scheduled(cron = "${scheduling.job.job1}")
    public void handle() throws Exception {

        JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis())
                .toJobParameters();
        JobLauncher.run(processJob, jobParameters);

    }

}

What am I missing?

amit
  • 11
  • 5

1 Answers1

1

You already got it yourself: With new DataWriter() you make your own instance without using Spring-Boot and therefore Spring-Boot does not have any chance to inject the dependencies you need.

Just inject your 'DataWriter' also with the @Autowired-Annotation (or with your own bean via @Bean) and you'll be fine. Hint: You could also use Constructor Injection which would be better because you are safe for circular dependencies.

the hand of NOD
  • 1,639
  • 1
  • 18
  • 30
  • perfect. Then you should provide your solution as accepted answer, so another one who has the problem benefits from it. Or, if my suggestion was the solution, you also can accept it as answer. – the hand of NOD Feb 19 '19 at 07:51