문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top