初始化 bean 中字段的顺序 [英] Order in which fields in a bean are initialized

查看:49
本文介绍了初始化 bean 中字段的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的豆子:

@Component
@DependsOn("SomeType")
Class A{

@Autowired
SomeType one;

String two = one.someMethod();

int three;

}

In my application context xml, I have:

<bean id="two" class="a.b.c.SomeType"></bean>

<context:component-scan base-package="a.b.c"/>
<context:annotation-config/>

但是当 Spring 实例化 bean 时,它抛出一个 NullPointerException.所以我想知道字段 two 是否在字段 one 之前初始化,导致 NPE.谁能告诉我在 bean 中初始化字段的顺序是什么?

But while Spring instantiates the bean, it throws a NullPointerException. So I'm wondering if the field two is initialized before field one, causing the NPE. Can anyone tell me in which order fields are initialized in a bean?

推荐答案

你的类A声明被编译成这个:

Your class A declaration is compiled into this one:

class A {
    @Autowired 
    SomeType one;
    String two;
    int three;

    public A() {
        this.two = one.someMethod();
    }
}

因此,当 Spring 创建 A 的实例以将 SomeType 的实例注入其中时,它会调用 A 的默认构造函数并因此你会得到一个 NPE.

So when Spring creates an instance of A to inject an instance of SomeType into it, it calls the A's default constructor and hence you get an NPE.

这篇关于初始化 bean 中字段的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆