【问题标题】:Spring Application context is null in a ApplicationContextAware classSpring Application 上下文在 ApplicationContextAware 类中为空
【发布时间】:2020-04-27 08:16:05
【问题描述】:

我在 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。在调试时,发现 applicationContext 没有被 Spring 正确初始化。

注意

是不是因为我开启了惰性bean初始化?

但是,我尝试通过 @Lazy(false) 和 Global application.yml 禁用延迟初始化,但没有帮助。

【问题讨论】:

  • 它是一个静态变量,你永远不会给它赋值。
  • 如何在静态变量中自动装配应用程序上下文?
  • @Stultuske 我使用与stackoverflow.com/questions/36985189/… 接受的答案完全相同的代码我需要将方法和变量设为静态。我怎样才能做到这一点?
  • @Stultuske 甚至静态变量也可以自动装配,因此使 applicationContext 不是问题。

标签: java spring spring-boot


【解决方案1】:

所以我自己弄清楚了这里出了什么问题。 我设置了全局惰性初始化,这是罪魁祸首。 由于我没有自动装配BeanProviderUtil,因此从未创建过bean,因此从未初始化过applicationContext

设置@Lazy(false) 解决了这个问题。

之前,在使用 @Lazy(false) 禁用 @Lazy 时它不起作用,因为 Spring 不知何故无法识别 BeanProviderUtil 组件。将@ComponentScan 添加到我的测试类就可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多