Reputation: 1321
I have two Spring Beans as follows:
@Service
public class A{
}
@Service
public class B{
@Autowired A a;
public B(){
a.doSomething();
}
The problem is that it is not guareenteed that A will be init earlier than B. So I will get a NullPointerException in B().
Is there anyway that I can specify this dependency in Spring?
Upvotes: 1
Views: 3724
Reputation: 773
Any autowiring in Spring framework will happen after the bean has been constructed. Therefore, it is not possible to use autowired members from the constructor itself (as seen in Autowired javadoc page). Your options are to either put the annotation on the constructor itself and make it accept the other bean as parameter which wil then work:
@Service
public class B {
@Autowired
public B(A a) {
a.doSomething();
}
}
or to use the @PostConstruct
annotation on a separate method which will be guaranteed to execute after the bean is constructed and will have all references wired correctly:
@Service
public class B{
@Autowired
A a;
@PostConstruct
public moreSetup() {
a.doSomething();
}
}
Upvotes: 6
Reputation: 140061
Spring is capable of detecting these dependencies automatically. It knows to create A before B based on the @Autowired
annotation (or more formally - when creating the instance of B, Spring detects that it needs an A, and will instantiate the A if it has not done so already).
Upvotes: 0