如何在 Spring Boot 应用程序中配置 DispatcherServlet?

2022-09-04 22:20:07

在传统的Spring Web应用程序中,是否可以覆盖,调用然后在返回的实例上设置以下init参数?AbstractDispatcherServletInitializer.createDispatcherServletsuper.createDispatcherServlet

setThreadContextInheritable
setThrowExceptionIfNoHandlerFound

如何在 Spring Boot 应用中实现此目的?


答案 1

您可以定义自己的配置并实现此目的,如下所示:

@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;
}

}


答案 2

对于任何试图解决这个问题的人,我们都是这样解决的:

@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);
  }
}

出于某种原因,当在调试模式下运行我们的spring boot应用程序时,Spring的overrode属性。在调试模式下,设置 servlet 就足够了。RequestContextFilterDispatcherServletThreadContextInheritable


推荐