在传统的Spring Web应用程序中,可以重写AbstractDispatcherServletInitializer.createDispatcherServlet
,调用super.createDispatcherServlet
,然后在返回的实例上设置以下init参数吗?
setThreadContextInheritable
setThrowExceptionIfNoHandlerFound
如何在Spring Boot应用程序中实现此目的?
最佳答案
您可以定义自己的配置并实现它,如下所示:
@Configuration
public class ServletConfig {
@Bean
public DispatcherServlet dispatcherServlet() {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
dispatcherServlet.setThreadContextInheritable(true);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return dispatcherServlet;
}
@Bean
public ServletRegistrationBean dispatcherServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet());
registration.setLoadOnStartup(0);
registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
return registration;
}
}