【问题标题】:`NullPointerException` due to failed autowiring`NullPointerException` 由于自动装配失败
【发布时间】:2016-01-21 08:25:00
【问题描述】:

我重构了Spring doc for creating batch service 以实现我的阅读器的独立类

@Component
@PropertySource("classpath:db-config.properties")
public class CsvReader<Item> extends FlatFileItemReader<Item>{

  @Autowired
  private Environment env;

  public CsvReader() {
    this.setResource(new ClassPathResource(env.getProperty("csv_file.name")));
    this.setLineMapper(new DefaultLineMapper<ImportDataItem>() {
      {
        setLineTokenizer(new DelimitedLineTokenizer() {
          {
            setNames(new String[] { "firstName", "lastName" });
          }
        });
      }
    });
  }
}

NullPointerExceptionenv.getProperty("csv_file.name") 抛出,如果它被替换为文件名的String,它就可以工作。我读过another answer 并且上面的代码看起来不错,所以你能帮我理解为什么Environment env 不是自动连线的吗?

[main] INFO org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5c29bfd: startup date [Thu Oct 22 11:26:18 IST 2015]; root of context hierarchy
[main] INFO org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader - Skipping bean definition for [BeanMethod:name=importDataJob,declaringClass=batch.spring.example.job.ImportDataJob]: a definition for bean 'importDataJob' already exists. This top-level bean definition is considered as an override.
[main] WARN org.springframework.context.annotation.ConfigurationClassEnhancer - @Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.
[main] WARN org.springframework.context.annotation.ConfigurationClassEnhancer - @Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.
[main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CsvReader' defined in batch.spring.example.job.ImportDataJob: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Factory method 'CsvReader' threw exception; nested exception is java.lang.NullPointerException
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
  at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
  at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
  at batch.spring.example.ImportDataApp.main(ImportDataApp.java:24)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Factory method 'CsvReader' threw exception; nested exception is java.lang.NullPointerException
  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
  ... 13 more
Caused by: java.lang.NullPointerException
  at batch.spring.example.job.item_reader.CsvReader.<init>(CsvReader.java:28)
  at batch.spring.example.job.ImportDataJob.CsvReader(ImportDataJob.java:67)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444.CGLIB$CsvReader$1(<generated>)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444$$FastClassBySpringCGLIB$$6d548885.invoke(<generated>)
  at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
  at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444.CsvReader(<generated>)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:497)
  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
  ... 14 more
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CsvReader' defined in batch.spring.example.job.ImportDataJob: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Factory method 'CsvReader' threw exception; nested exception is java.lang.NullPointerException
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
  at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
  at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
  at batch.spring.example.ImportDataApp.main(ImportDataApp.java:24)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Factory method 'CsvReader' threw exception; nested exception is java.lang.NullPointerException
  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
  ... 13 more
Caused by: java.lang.NullPointerException
  at batch.spring.example.job.item_reader.CsvReader.<init>(CsvReader.java:28)
  at batch.spring.example.job.ImportDataJob.CsvReader(ImportDataJob.java:67)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444.CGLIB$CsvReader$1(<generated>)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444$$FastClassBySpringCGLIB$$6d548885.invoke(<generated>)
  at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
  at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444.CsvReader(<generated>)
  at sun.reflect.NativeMethodAccessorImpl.inv    [main] INFO org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5c29bfd: startup date [Thu Oct 22 11:26:18 IST 2015]; root of context hierarchy
[main] INFO org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader - Skipping bean definition for [BeanMethod:name=importDataJob,declaringClass=batch.spring.example.job.ImportDataJob]: a definition for bean 'importDataJob' already exists. This top-level bean definition is considered as an override.
[main] WARN org.springframework.context.annotation.ConfigurationClassEnhancer - @Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.
[main] WARN org.springframework.context.annotation.ConfigurationClassEnhancer - @Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.
[main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CsvReader' defined in batch.spring.example.job.ImportDataJob: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Factory method 'CsvReader' threw exception; nested exception is java.lang.NullPointerException
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
  at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
  at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
  at batch.spring.example.ImportDataApp.main(ImportDataApp.java:24)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Factory method 'CsvReader' threw exception; nested exception is java.lang.NullPointerException
  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
  ... 13 more
Caused by: java.lang.NullPointerException
  at batch.spring.example.job.item_reader.CsvReader.<init>(CsvReader.java:28)
  at batch.spring.example.job.ImportDataJob.CsvReader(ImportDataJob.java:67)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444.CGLIB$CsvReader$1(<generated>)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444$$FastClassBySpringCGLIB$$6d548885.invoke(<generated>)
  at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
  at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444.CsvReader(<generated>)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:497)
  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
  ... 14 more
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CsvReader' defined in batch.spring.example.job.ImportDataJob: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Factory method 'CsvReader' threw exception; nested exception is java.lang.NullPointerException
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
  at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
  at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
  at batch.spring.example.ImportDataApp.main(ImportDataApp.java:24)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Factory method 'CsvReader' threw exception; nested exception is java.lang.NullPointerException
  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
  at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
  ... 13 more
Caused by: java.lang.NullPointerException
  at batch.spring.example.job.item_reader.CsvReader.<init>(CsvReader.java:28)
  at batch.spring.example.job.ImportDataJob.CsvReader(ImportDataJob.java:67)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444.CGLIB$CsvReader$1(<generated>)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444$$FastClassBySpringCGLIB$$6d548885.invoke(<generated>)
  at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
  at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
  at batch.spring.example.job.ImportDataJob$$EnhancerBySpringCGLIB$$eb882444.CsvReader(<generated>)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:497)
  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
  ... 14 more

【问题讨论】:

  • 能分享一下环境源码和context.xml吗?
  • 还有为什么你在env.getProperty("csv.filename")的文件名之前有文件类型csv,不应该是env.getProperty("filename.csv")吗?
  • @AmirAl 该属性包含 csv 文件的文件名。第二个选项会令人困惑,因为看起来有一个名为 filename.csv 的文件而不是一个属性。
  • @Kayaman 哦,好吧,那就解释了有关命名的全部内容。我认为它会根据文件的名称和类型读取文件,但看起来你正在指示一个属性名称:)
  • @AmirAl,只是为了提高可读性,我将csv.filename 更改为csv_file.name :)

标签: java spring autowired properties-file


【解决方案1】:

这一切都归结为对象的构造和自动装配方式。要构造一个对象,必须调用构造函数。然后你有一个对象的引用,并且可以设置它的字段。这就是 Spring 在创建 bean 并自动装配它们时所做的事情:它调用构造函数,然后设置所有带有 @Autowired 注释的字段。它不能在调用构造函数之前设置一个字段,因为它还没有任何对象。

但是您的构造函数尝试访问应该由 Spring 自动装配的字段,甚至在对象被构造之前。这不可能发生。

要从构造函数访问自动装配的 bean,必须使用构造函数注入。另一种选择是将所有这些代码从构造函数移动到使用@PostConstruct 注释的方法。

【讨论】:

  • 感谢@jb-nizet,添加@ComponentScan("batch.spring.example") 解决了错误:)
猜你喜欢
  • 2019-09-20
  • 2013-12-25
  • 2017-04-04
  • 1970-01-01
  • 2018-02-21
  • 2012-03-19
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多