【发布时间】:2020-01-07 07:31:54
【问题描述】:
我有一个像下面这样的子类:-
@Component
public class Subclass extends Superclass {
//few inherited methods implementation
}
Superclass is like below:-
@Component
public class Superclass implements InterfaceA {
@Autowired
@Qualifier("envBean")
private EnvironmentBean envBean;
private DateTime effective_date = envBean.getProperty("effective.date");
}
现在在部署应用程序时,我遇到以下错误
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name "Subclass"
Constructor threw exception; nested exception is java.lang.NullPointerException
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [Subclass]:Constructor threw exception; nested exception is java.lang.NullPointerException.
我终于看到了——
Caused by: java.lang.NullPointerException: null
at Superclass <init> (SuperClass.java:{lineNumber}
在下面一行:-
**envBean.getProperty("effective.date");**
我已经尝试使用来自子类本身的 EnvironmentBean 属性的构造函数注入 尝试在 xml 中配置它并使用构造函数注入实例化超类 bean。 有人知道如何解决吗?
【问题讨论】:
-
请使用
envBeanbean 的配置更新您的问题。 -
在两个类中都使用构造函数注入。
envBean.getProperty("effective.date");在构造 bean 时调用。并且 Spring 不可能在构建 bean 之前设置 bean 的字段的值。所以当该行执行时,envBean 保证为空。 -
在构造对象之后,自动装配字段可用。所以在构造函数中访问它们是行不通的。如果需要,可以使用构造函数注入,或者直接使用
@Value获取属性,而不是自己检索。
标签: java spring dependency-injection autowired