![](/img/trans.png)
[英]EMenuService throwing nullpointerException in @postConstruct
[英]Why @PostConstruct causes NullPointerException?
我正在学习Spring Framework,同时观看Evgeniy Borisov的演讲时遇到了以下代码:
假设我们有两个具有循环依赖关系的bean:
第二粒豆:
@Service
public class Two {
@Autowired
private One one;
public String getWord() {
return word;
}
private String word;
@PostConstruct
public void doSmth(){
init();
System.out.println("SECOND BEAN TEXT :"+one.getWord());
}
public void init(){
word = "Second word";
}
}
第一个豆:
@Service
public class One {
@Autowired
private Two two;
public String getWord() {
return word;
}
private String word;
@PostConstruct
public void doSmth(){
init();
System.out.println("FIRST BEAN TEXT :"+two.getWord());
}
public void init(){
word = "First bean";
}
}
并开始上课:
public class StartTests {
public static void main(String[] args) {
AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext("test");
}
}
如果执行StartTests类,我们将在输出中得到它:
第二个纯文本:空
第一篇课文:第二个字
是的,我知道@PostConstructor在涉及所有代理之前执行,但是我不明白为什么First Bean可以正常工作而Second Bean无法正常工作
这只是关于执行顺序。 其中之一必须首先运行!
@Autowiring
运行(工作正常) @PostConstruct
在你的, One
的@PostConstruct恰好先运行,那么Two
的算账。
如果希望Bean One
在Two
之前初始化,则可以添加@DependsOn
@DependsOn({"One"})
@Service
public class Two {
可以用于直接或间接用Component注释的任何类,或用Bean注释的方法。
尽管您在其他日志中将得到null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.