java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present

@Controller
@ComponentScan
@Configuration
@EnableScheduling
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, RedisAutoConfiguration.class, MybatisAutoConfiguration.class})
@ImportResource(locations = {"classpath*:app.xml"})
public class AppMain extends SpringBootServletInitializer implements ApplicationContextAware {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
// return super.configure(builder);
return builder.sources(AppMain.class);
}

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.setInitParameter("logSystem","log4j,logback");
servletContext.setInitParameter("loggingLevel", "INFO");
servletContext.setInitParameter("loggingCharset", "UTF-8");
servletContext.setInitParameter("contextConfigLocation", "<NONE>");
super.onStartup(servletContext);
}
}



 

For anyone with a similar problem - turns out that spring-jersey used in the project was setting up its own context. My context and the spring-jersey one were initialized in random order apparently. More info here: 
https://java.net/jira/browse/JERSEY-2038 
https://java.net/projects/jersey/lists/users/archive/2014-03/message/124 
The suggested solution of adding:

servletContext.setInitParameter("contextConfigLocation", "<NONE>");

In WebAppInitializer implementation didn't work reliably due to initialization order. What solved the problem was adding its xml equivalent: 

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value></param-value>
</context-param> 

as the firt parameter in web.xml, ensuring that its set before the context is initialized.

posted @ 2019-06-26 19:42  牧之丨  阅读(3037)  评论(0编辑  收藏  举报