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?
The DispatcherServlet is the front controller in Spring web applications. It's used to create web applications and REST services in Spring MVC. In a traditional Spring web application, this servlet is defined in the web. xml file.
A typical MVC database driven Spring MVC application requires a lot of configuration such as dispatcher servlet, a view resolver, Jackson, data source, transaction manager, among many others. Spring Boot auto-configures a Dispatcher Servlet if Spring MVC jar is on the classpath.
When DispatcherServlet is loaded, it looks for the bean configuration file of WebApplicationContext and initializes it. By having access to Servlet context, any spring bean which implement ServletConextAware interface – can get access to ServletContext instance and do many things with it.
The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class), and as such is declared in the web. xml of your web application. Requests that you want the DispatcherServlet to handle will have to be mapped using a URL mapping in the same web. xml file.
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. In debug mode setting the servlet is enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With