Use servlet context that can access classloader

Update `SpringBootServletInitializer` to use the `ServletContext` that
was provided to the initial `onStartup` call rather than the
one from the `ServletContextEvent`. This allows the `getClassLoader()`
call to complete without throwing an `UnsupportedOperationException`.

Fixes gh-21684
This commit is contained in:
Phillip Webb
2020-06-03 19:14:52 -07:00
parent 29253264b4
commit 4d37430bfe

View File

@@ -92,27 +92,9 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit
// Logger initialization is deferred in case an ordered
// LogServletContextInitializer is being used
this.logger = LogFactory.getLog(getClass());
WebApplicationContext rootAppContext = createRootApplicationContext(servletContext);
if (rootAppContext != null) {
servletContext.addListener(new ContextLoaderListener(rootAppContext) {
@Override
public void contextInitialized(ServletContextEvent event) {
// no-op because the application context is already initialized
}
@Override
public void contextDestroyed(ServletContextEvent event) {
try {
super.contextDestroyed(event);
}
finally {
deregisterJdbcDrivers(event.getServletContext());
}
}
});
WebApplicationContext rootApplicationContext = createRootApplicationContext(servletContext);
if (rootApplicationContext != null) {
servletContext.addListener(new SpringBootContextLoaderListener(rootApplicationContext, servletContext));
}
else {
this.logger.debug("No ContextLoaderListener registered, as createRootApplicationContext() did not "
@@ -212,6 +194,10 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit
return builder;
}
/**
* {@link ApplicationListener} to trigger
* {@link ConfigurableWebEnvironment#initPropertySources(ServletContext, javax.servlet.ServletConfig)}.
*/
private static final class WebEnvironmentPropertySourceInitializer
implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
@@ -236,4 +222,34 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit
}
/**
* {@link ContextLoaderListener} for the initialized context.
*/
private class SpringBootContextLoaderListener extends ContextLoaderListener {
private final ServletContext servletContext;
SpringBootContextLoaderListener(WebApplicationContext applicationContext, ServletContext servletContext) {
super(applicationContext);
this.servletContext = servletContext;
}
@Override
public void contextInitialized(ServletContextEvent event) {
// no-op because the application context is already initialized
}
@Override
public void contextDestroyed(ServletContextEvent event) {
try {
super.contextDestroyed(event);
}
finally {
// Use original context so that the classloader can be accessed
deregisterJdbcDrivers(this.servletContext);
}
}
}
}