问题
I have a Spring Batch project with multiple jobs (job A, job B, job C,...). When I run a particular job A, I got the log of the job A shows that all of the beans of job B, C,... are created too. Is there any way to avoid the creation of the other beans when job A is launched.
I have tried to use @Lazy annotation but it 's seem not working.
@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Autowired
@Qualifier("springDataSource")
public DataSource springDataSource;
@Autowired
@Qualifier("batchJobDataSource")
public DataSource batchJobDataSource;
}
@Configuration
@PropertySource("classpath:partner.properties")
public class B extends BatchConfiguration {
@Value("${partnerId}")
private String partnerId;
@Lazy
@Bean
public Job ProcessB(JobCompletionNotificationListener listener) {
return jobBuilderFactory
.get("ProcessB")
.incrementer(new RunIdIncrementer())
.listener(listener)
.start(ProcessStepB())
.build();
}
@Lazy
@Bean
public Step (ProcessStepB() {
return stepBuilderFactory
.get("(ProcessStepB")
.<PartnerDTO, PartnerDTO> chunk(1)
.reader(getPartner())
.processor(process())
.writer(save())
.build();
}
@Lazy
@Bean(destroyMethod = "")
public Reader getPartner() {
return new Reader(batchJobDataSource,partnerId);
}
@Lazy
@Bean
public Processor process() {
return new Processor();
}
@Lazy
@Bean
HistoryWriter historyWriter() {
return new HistoryWriter(batchJobDataSource);
}
@Lazy
@Bean
UpdateWriter updateWriter() {
return new UpdateWriter(batchJobDataSource);
}
@Lazy
@Bean
public CompositeItemWriter<PartnerDTO> saveTransaction() {
List<ItemWriter<? super PartnerDTO>> delegates = new ArrayList<>();
delegates.add(updateWriter());
delegates.add(historyWriter());
CompositeItemWriter<PartnerDTO> itemWriter = new CompositeItemWriter<>();
itemWriter.setDelegates(delegates);
return itemWriter;
}
}
I have also put the @Lazy over the @Configuration but it does work too.
回答1:
That should not be an issue. But here are a few ideas to try:
- Use Spring profiles to isolate job beans
- If you use Spring Boot 2.2+, try to activate the lazy bean initialization mode
- Package each job in its own jar. This is the best option IMO.
来源:https://stackoverflow.com/questions/60349214/how-to-apply-something-like-lazy-to-spring-batch