繁体   English   中英

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

也许您可以尝试 interface -> InitializingBean ,并覆盖方法“afterPropertiesSet”,然后您可以分配 Effective_date 值。 就像:

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

似乎这是因为 Spring 必须首先创建类Superclass的实例,然后才注入EnvironmentBean 也就是说,当类Superclass被实例化时,即使在 Spring 尝试注入依赖@Autowired @Qualifier("envBean") private EnvironmentBean envBean;之前,Java 也会尝试实例化字段DateTime effective_date @Autowired @Qualifier("envBean") private EnvironmentBean envBean; . 此时envBean指的是null 因此,这肯定会引发 NPE。 (我的看法。)

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

必须有一个名为EnvironmentBean的类它必须用文档https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/package-summary 中显示的任何一种 Spring 构造型进行注释。 html

组件- 表示带注释的类是“组件”。

控制器- 表示带注释的类是“控制器”

索引- 指示带注释的元素表示索引的构造型。

存储库- 表示带注释的类是“存储库”,最初由领域驱动设计(Evans,2003 年)定义为“一种用于封装存储、检索和搜索行为的机制,它模拟对象集合”。

服务- 表示带注释的类是“服务”,最初由领域驱动设计(Evans,2003 年)定义为“作为独立于模型中的接口提供的操作,没有封装状态”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM