springboot中使用ContextLoaderListener.getCurrentWebApplicationContext();获取WebApplicationContext为空问题

WebApplicationContext applicationContext =  ContextLoaderListener.getCurrentWebApplicationContext();

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

经过上网查询缘由已解决,方法以下:spring

@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; } }

再使用:tomcat

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

获取不到的缘由:springboot不管以main方法仍是spring-boot:run的方式执行都不会跑SpringBootServletInitializer中的onStartup致使ContextLoaderListener没有执行。springboot

考虑到以往的经验ContextLoaderListener通常是配置在web.xml中的对web容器有依赖,因此我直接把工程打成war放到tomcat跑果真能够调用SpringBootServletInitializer中的onStartup,app

可是仍是不能获取ContextLoader.getCurrentWebApplicationContext(),缘由是在onStartup初始化ContextLoader时使用的是构造函数,没有用ContextLoader.initWebApplicationContext方式,ide

因此获取不到,要用这种方式得重写SpringBootServletInitializer中的onStartup。函数

解决方法来自:http://www.oschina.net/question/2416168_2189114spring-boot

相关文章
相关标签/搜索