java - 为什么@PostConstruct 会导致 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 类,我们将在输出中得到:
第二个 Bean 文本:null
FIRST BEAN TEXT :第二个字
是的,我知道 @PostConstructor 在涉及所有代理之前执行,但我不明白为什么 First Bean 可以正常工作,而 Second Bean 不能
解决方案
这只是关于执行顺序。 毕竟其中一个必须先运行!
- 春天贯穿所有
@Autowiring
(工作正常) - Spring以某种顺序贯穿所有的
@PostConstruct
s
在您的情况下,One
's @PostConstruct 恰好首先运行,然后是 THEN Two
。
推荐阅读
- angular - Angular 材质 datepiker 配置时间
- python - 基于多重关系优化模型设计
- php - 如何将 PHP 参数传递到 system32 文件夹中的 bat 文件中
- angular - 角度 HttpClient 请求返回 404。链接是 actif
- flutter - Flutter:ClipRRect 与带有 BoxDecoration 的容器
- php - 如何使用onclick按钮请求php api
- networking - 如何找到网络中两个节点之间的延迟、带宽和吞吐量?
- android - 如何通过 suspendCancellableCoroutine 防止使用 try catch
- c# - 为多个进程存储多个 UNC 路径
- python-3.x - 对具有多个输入调用的函数进行单元测试的效率如何?