Spring 超类中带有@Autowire 的bean

Spring bean with @Autowire in superclass

我有一个如下的子类:-

@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 中配置它并使用构造函数注入实例化 Superclass bean。 有人知道如何解决吗?

必须有一个名为 EnvironmentBean 的 class 它必须用 doc https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/package-summary.html[= 中显示的 Spring 构造型中的任何一个进行注释12=]

Component - Indicates that an annotated class is a "component".

Controller - Indicates that an annotated class is a "Controller"

Indexed - Indicate that the annotated element represents a stereotype for the index.

Repository - Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects".

Service - Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state."

也许你可以尝试接口 -> InitializingBean,并覆盖方法 'afterPropertiesSet',然后你可以分配 effective_date 值。就像:

@Override
public void afterPropertiesSet() {
    effective_date = envBean.getProperty("effective.date");
}

这似乎是因为 Spring 必须首先创建 class Superclass 的实例,然后才注入 EnvironmentBean。也就是说,当 class Superclass 被实例化时,Java 甚至会在 Spring 尝试注入依赖项 [=14= 之前尝试实例化字段 DateTime effective_date ].此时envBean指的是null。因此,这肯定会引发 NPE。 (我的看法。)

所以,不确定这是否真的与 class 层次结构本身有关。