[英]How to configure DispatcherServlet in a Spring Boot application?
In a traditional Spring Web app, it's possible to override AbstractDispatcherServletInitializer.createDispatcherServlet
, call super.createDispatcherServlet
and then set the following init parameters on the returned instance? 在传统的Spring Web应用程序中,可以覆盖
AbstractDispatcherServletInitializer.createDispatcherServlet
,调用super.createDispatcherServlet
,然后在返回的实例上设置以下init参数?
setThreadContextInheritable
setThrowExceptionIfNoHandlerFound
How do I achieve this in a Spring Boot app? 如何在Spring Boot应用程序中实现此目的?
You can define your own configuration and achieve this, as shown below: 您可以定义自己的配置并实现此目的,如下所示:
@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;
}
} }
For anyone trying to solve this issue, we solved it this way : 对于任何试图解决此问题的人,我们都是这样解决的:
@Configuration
public class ServletConfig {
@Autowired
RequestContextFilter filter;
@Autowired
DispatcherServlet servlet;
@PostConstruct
public void init() {
// Normal mode
filter.setThreadContextInheritable(true);
// Debug mode
servlet.setThreadContextInheritable(true);
servlet.setThrowExceptionIfNoHandlerFound(true);
}
}
For some reason, when running our spring boot application NOT in debug mode, Spring's RequestContextFilter
overrode DispatcherServlet
ThreadContextInheritable
property. 出于某种原因,当我们的Spring启动应用程序
RequestContextFilter
调试模式下运行时,Spring的RequestContextFilter
覆盖DispatcherServlet
ThreadContextInheritable
属性。 In debug mode setting the servlet is enough. 在调试模式下设置servlet就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.