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