请注意访问的最佳实践
ServletContext:您不应在主应用程序类中进行操作,而应在例如控制器中进行操作。
否则,请尝试以下操作:
实现
ServletContextAware接口,Spring会为您注入。
删除
@Autowired该变量。
添加
setServletContext方法。
@SpringBootApplicationpublic class MyApp implements ServletContextAware { private BeanThing beanThing = null; private ServletContext servletContext; public MyApp() { // Lots of stuff goes here. // no reference to servletContext, though // beanThing gets initialized, and mostly populated. } @Bean public BeanThing getBeanThing() { return beanThing; } @PostConstruct public void populateContext() { // all references to servletContext go here, including the // bit where we call the appropriate setters in beanThing } public void setServletContext(ServletContext servletContext) { this.context = servletContext; }}


