我有一个子类如下:-
@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。有人知道怎么解决吗?
发布于 2020-01-07 07:59:33
也许您可以尝试接口InitializingBean,和->重写方法'afterPropertiesSet',然后您可以分配effective_date值。就像:
@Override
public void afterPropertiesSet() {
effective_date = envBean.getProperty("effective.date");
}发布于 2020-01-07 08:13:32
这似乎是因为Spring必须首先创建类Superclass的实例,然后才注入EnvironmentBean。也就是说,当类Superclass被实例化时,DateTime effective_date将尝试实例化字段DateTime effective_date,甚至在Spring尝试注入依赖项@Autowired @Qualifier("envBean") private EnvironmentBean envBean;之前。此时,envBean指的是null。因此,这肯定会引发NPE。(我的看法)
因此,不确定这是否真的与类层次结构本身有关。
发布于 2020-01-07 07:38:55
必须有一个名为EnvironmentBean的类,必须用文档https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/package-summary.html中显示的任何一个Spring原型对其进行注释
Component --表示带注释的类是“组件”。
Controller -指示带注释的类是“控制器”
索引--表示带注释的元素表示索引的构造型。
Repository --表示带注释的类是"Repository",最初由领域驱动设计(Evans,2003)定义为“封装存储、检索和搜索行为的机制,该机制模拟对象的集合”。
Service --表示带注释的类是“服务”,最初由领域驱动设计(Evans,2003)定义为“作为独立于模型的接口提供的操作,没有封装状态”。
https://stackoverflow.com/questions/59624000
复制相似问题