Can a Spring component's constructor refer to an @Autowired component, or does the autowiring happen too late?
I have an example that's something like this:
@Component
public class A {
public A() { ... }
...
}
@Component
public class B {
@Autowired A a;
public B() {
some code using a.getThisOrThat() ... // fails, a is null
}
}
and in the config file:
<bean id="a" class="some.packagename.A" />
<bean id="b" class="some.packagename.B" depends-on="a" />
I've confirmed using System.out.println
that A's constructor is called before B's; however, inside B's constructor, a
is null. I'm running this as a JUnit unit test, using SpringJUnit4ClassRunner
. If I defer the initialization in B
until the first time another method is called, it works fine--a
has been set up.
Is this the expected behavior?
Is it possible that the behavior is different when SpringJUnit4ClassRunner
is being used?
Is there a way to get this to work (aside from deferring the initialization in B
)?