问题
when I running a project of spring batch, exception occured!
Exception detail:
Caused by: java.lang.NullPointerException: null
at org.springframework.batch.item.xml.StaxEventItemReader.moveCursorToNextFragment(StaxEventItemReader.java:141)
fileName is correct!
configuration code:
@Bean
@StepScope
public StaxEventItemReader xmlFileItemReader(@Value("#{jobParameters['fileType']}") String fileType,
@Value("#{jobExecutionContext['extractFileName']}") String fileName) throws Exception {
System.out.println("======================== fileName =========================="+fileName);
StaxEventItemReader reader = new StaxEventItemReader();
reader.setResource(new FileSystemResource(fileName));
reader.setFragmentRootElementName("PortData");
reader.setUnmarshaller(unmarshaller());
reader.afterPropertiesSet();
return reader;
}
回答1:
I wish I could comment on Padis response, as it put me on track for finding the solution.
I had the same nullPointerException problem with a reader and a writer scoped in @StepScope.
Padis is totally right, when he writes that, when the type of the @Bean is ItemReader or ItemWriterthe doOpen() function is not called (It causes the NullPointerException)
It happens that, changing the type of my beans from ItemReader<T> to ItemStreamReader<T> and ItemWriter<T> to ItemStreamWriter<T> was the solution for me.
回答2:
Before all check this thread and check if your xml file is composed by a single object element like:
<Object>
<child1>...</child1>
<child2>...</child2>
<child3>...</child3>
</Object>
because StAX reader implementation works for files like
<root>
<Object>...</Object>
<Object>...</Object>
<root>
If this solve the problem, stop reading!
Else apparently there aren't errors in your configuration.
Assuming latest version (2.2.1.RELEASE)
Error is in this line at StaxEventItemReader.moveCursorToNextFragment()
while (reader.peek() != null && !reader.peek().isStartElement()) {
so, most probably, reader is null; or you have unmarshal problems and reader go into trouble.
Is error thrown at first read or after a random number of reads?
Put a breakpoint in check StaxEventItemReader.doOpen() or set log level to debug and look if something goes wrong-
回答3:
I am having similar problem right now. With @StepScope set on the reader open() method is not called.
TaskletStep calls open() on CompositeItemStream when step is executed. It calls open on every ItemStream. The reader with @StepScope does not seem to be set on CompositeItemStream.
Make sure that step builder registers your reader in SimpleStepBuilder.registerAsStreamsAndListeners(). The problem that I had was that type of my reader bean was ItemReader and proxied registered it is not instance of ItemStream. Changing the type of my reader bean to ItemStream (StaxEventItemReader) fixed the problem.
来源:https://stackoverflow.com/questions/18377966/spring-batch-staxeventitemreader-release-out-an-exception