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

时间:2016-02-01 00:40:35

标签: java spring spring-mvc servlets spring-boot

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

setThreadContextInheritable
setThrowExceptionIfNoHandlerFound

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

2 个答案:

答案 0 :(得分:2)

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

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

}

答案 1 :(得分:0)

对于试图解决此问题的任何人,我们都是通过以下方式解决的:

@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的RequestContextFilter会覆盖DispatcherServlet ThreadContextInheritable属性。在调试模式下,设置servlet就足够了。