I have a bean like this:
@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/>
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?
Your class A
declaration is compiled into this one:
class A {
@Autowired
SomeType one;
String two;
int three;
public A() {
this.two = one.someMethod();
}
}
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
.
First I have to say that String two = one.someMethod();
this line of code is very very bad. Then let me explain how the NPE happens. When the Spring instants the beans, first it instant the bean: A
, then try to bind the field one
, at this time, the bean SomeType may not be instanted, so the Sping will mark it as await to instant
and then goes on to bind the other field, it move to instant two
, then cause problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.