我有这样的豆:
@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中初始化哪个顺序字段?
答案 0 :(得分:3)
您的班级A
声明已汇编到此声明中:
class A {
@Autowired
SomeType one;
String two;
int three;
public A() {
this.two = one.someMethod();
}
}
因此,当Spring创建A
的实例以向其中注入SomeType
的实例时,它会调用A
的默认构造函数,因此您得到NPE
1}}。
答案 1 :(得分:1)
首先我要说String two = one.someMethod();
这行代码非常糟糕。然后让我解释一下NPE是如何发生的。当Spring暂时关闭bean时,首先它会立即调用bean A
,然后尝试绑定字段one
,此时,Bean可能不会被实例化,因此Sping会将其标记为await to instant
然后继续绑定其他字段,它会转到即时two
,然后导致问题。