我在 ApplicationContextAware
类中收到 NullPointerException,但我不确定为什么。
为什么调用 getBean(SomeClass.class)
方法时 applicationContext
为 null
以下是我的 BeanProviderUtil 类:
@Component
public class BeanProviderUtil implements ApplicationContextAware {
public static ApplicationContext applicationContext;
public static <T extends Object> T getBean(Class<T> beanClass) {
return applicationContext.getBean(beanClass);
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanProviderUtil.applicationContext = applicationContext;
}
}
调用函数时
SomeOtherClass obj = BeanProviderUtil.getBean(SomeOtherClass.class)
我正在获得 NPE。调试时发现 Spring 未正确初始化 applicationContext。
注意
是不是因为我启用了惰性bean初始化?
但是,我尝试通过 @Lazy(false)
以及 Global application.yml
禁用延迟初始化,但没有帮助。
最佳答案
所以我自己弄清楚了这里出了什么问题。
我设置了全局延迟初始化,这是罪魁祸首。
由于我没有 Autowiring BeanProviderUtil
,所以该 bean 从未被创建,因此 applicationContext
从未被初始化。
设置@Lazy(false)
修复了该问题。
之前,在使用 @Lazy(false)
禁用 @Lazy 时,它不起作用,因为 Spring 无法识别 BeanProviderUtil
组件。将 @ComponentScan
添加到我的测试类即可解决问题。
关于java - Spring应用程序上下文在ApplicationContextAware类中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61454424/