zoukankan      html  css  js  c++  java
  • springboot中使用ContextLoaderListener.getCurrentWebApplicationContext();获取WebApplicationContext为空问题

    WebApplicationContext applicationContext =  ContextLoaderListener.getCurrentWebApplicationContext();

    在springboot 2.0.0.M7 版本中遇到使用以上代码获取 WebApplicationContext 为null的问题。

    通过上网查询原因已解决,方法如下:

    @Component
    @Lazy(false)
    public class ApplicationContextRegister implements ApplicationContextAware {
        private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextRegister.class);
        private static ApplicationContext APPLICATION_CONTEXT;
    
        /**
         * 设置spring上下文  *  * @param applicationContext spring上下文  * @throws BeansException
         */
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            LOGGER.debug("ApplicationContext registed-->{}", applicationContext);
            APPLICATION_CONTEXT = applicationContext;
        }
    
        public static ApplicationContext getApplicationContext() {
            return APPLICATION_CONTEXT;
        }
    }

    再使用:

    CrawlerService crawlerService = ApplicationContextRegister.getApplicationContext().getBean(CrawlerService.class);

    获取不到的原因:springboot无论以main方法还是spring-boot:run的方式执行都不会跑SpringBootServletInitializer中的onStartup导致ContextLoaderListener没有执行。

    考虑到以往的经验ContextLoaderListener一般是配置在web.xml中的对web容器有依赖,所以我直接把工程打成war放到tomcat跑果然可以调用SpringBootServletInitializer中的onStartup,

    但是还是不能获取ContextLoader.getCurrentWebApplicationContext(),原因是在onStartup初始化ContextLoader时使用的是构造函数,没有用ContextLoader.initWebApplicationContext方式,

    所以获取不到,要用这种方式得重写SpringBootServletInitializer中的onStartup。

    解决方法来自:http://www.oschina.net/question/2416168_2189114

  • 相关阅读:
    python斐波那契数列
    python装饰器
    Python文件操作
    python 第三方库的安装方法
    Ajax 基本使用学习记录
    微分方程概述
    Typora中的数学公式
    Ubuntu20.04 安装 mysql8.0 之后 root 账户无法登录
    Ubuntu20.04换源之后依旧慢?如何更有效的换源
    Ubuntu18.04更新python版本
  • 原文地址:https://www.cnblogs.com/zhuzhen/p/8582504.html
Copyright © 2011-2022 走看看