Order in which fields in a bean are initialized

╄→гoц情女王★ 提交于 2020-01-14 06:16:18

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/15627792/order-in-which-fields-in-a-bean-are-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!