Reputation: 24637
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?
setThreadContextInheritable
setThrowExceptionIfNoHandlerFound
How do I achieve this in a Spring Boot app?
Upvotes: 13
Views: 17549
Reputation: 41
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. In debug mode setting the servlet is enough.
Upvotes: 4
Reputation: 1895
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;
}
}
Upvotes: 6