setApplicationContext 空指针
时间: 2023-08-26 15:08:11 浏览: 102
获取spring容器的方法
根据引用\[1\]的描述,出现空指针异常的原因是在调用setApplicationContext方法之前,applicationContext没有被正确实例化。为了解决这个问题,可以按照引用\[2\]中的建议,在主类上使用@Import注解导入getBean方法所在的类。具体做法是在@SpringBootApplication注解的类上添加@Import(SpringContextHolder.class),如下所示:
```java
@SpringBootApplication
@Import(SpringContextHolder.class)
public class AdminApplication {
public static void main(String\[\] args) {
SpringApplication.run(AdminApplication.class, args);
}
}
```
这样做可以确保在调用setApplicationContext方法之前,applicationContext已经被正确实例化,从而避免空指针异常的问题。
#### 引用[.reference_title]
- *1* [实现ApplicationContextAware接口后调用时候报空指针NullPointerException异常](https://blog.csdn.net/CrazyRango/article/details/115556255)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [SpringBoot - 获取getBean方法以及ApplicationContext空指针问题解决](https://blog.csdn.net/hutuyaoniexi/article/details/126787251)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文