I am using Spring4.
There are three beans: bean1
and bean2
and bean3
,and in my bean1's @PostConstruct
method,i invoke bean2's method,this method of bean2
will invoke bean3's method,and i got a NPE, beacuse method in bean2
is invoked, bean3
hasn't been injected yet.
How to avoid this kind of situation? The code looks something like this:
@Service
public class Bean1 {
@Autowired
private Bean2 bean2;
@PostConstruct
public void init() {
// invoke bean2's method
bean2.test();
}
}
@Service
public class Bean2 {
@Autowired
private Bean3 bean3;
public void test() {
// invoke bean3's method,got a null pointer ex,because bean3 is null.
bean3.xxx();
}
}
What Ever code posted by you, I don't thing you may get any problem. Just Check in your whole code you are creating bean yourself not by spring its only one case.
If you are creating bean yourself then spring wont be inject anything and provide bean object as null. post
You need the @DependsOn
annotation to make sure bean initialization happens in the order you expect.
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.