0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

spring-batchのpartitioning使用時のReader must be open before it can be readの原因と対策

Last updated at Posted at 2020-01-22

現象

以下のようなbean定義をしたところエラーになり実行できなかった。

やろうとした事としては https://docs.spring.io/spring-batch/docs/current/reference/html/scalability.html#partitioning の、spring-batchのPartitioningを試している。partitioningの情報(fileName)がstepExecutionContextに入るため、beanを@StepScopeにしている。

	@StepScope
	@Bean
	public ItemReader<String> itemReader(@Value("#{stepExecutionContext['fileName']}") 
	Resource resource) throws IOException {

エラー内容は以下のとおり。

org.springframework.batch.item.ReaderNotOpenException: Reader must be open before it can be read.
	at org.springframework.batch.item.file.FlatFileItemReader.readLine(FlatFileItemReader.java:201) ~[spring-batch-infrastructure-4.2.1.RELEASE.jar:4.2.1.RELEASE]
	at org.springframework.batch.item.file.FlatFileItemReader.doRead(FlatFileItemReader.java:178) ~[spring-batch-infrastructure-4.2.1.RELEASE.jar:4.2.1.RELEASE]

対策

戻り値型のItemReaderFlatFileItemReaderに変更する。または、この場合はItemStreamReaderでも良い。

	@StepScope
	@Bean
	public FlatFileItemReader<String> itemReader(@Value("#{stepExecutionContext['fileName']}") 
	Resource resource) throws IOException {

理由

@StepScopeにより戻り値をAOPでプロキシするため。

@StepScopeの中身を見るとproxyMode = ScopedProxyMode.TARGET_CLASSであり、いま、戻り値型がItemReaderなのでこのインタフェースに対するプロキシが作られる。そして、このインタフェースには(ItemStreamの)openは無いので、当然openは呼ばれない。実際のインスタンスはFlatFileItemReaderでこれはopenせずにreadは出来ないため、Reader must be open before it can be readという例外になる。そういわけで戻り値型をFlatFileItemReaderか、ItemStreamReaderに変えれば正常に動作する。

参考URL

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?