2

throwExceptionIfNoHandlerFound was introduced in DispatcherServlet in Spring 4.0.

I have tried to figure out how to set this property in the autoconfigured DispatcherServlet provided by Spring Boot, but no luck.

Some digging suggests the snippet below should work, but it doesn't.

@Bean
public ServletContextInitializer servletContextInitializer() {
    return new ServletContextInitializer() {
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            servletContext.setInitParameter("throwExceptionIfNoHandlerFound", "true");

        }
    };
}  
Dave Syer
  • 56,583
  • 10
  • 155
  • 143
bep
  • 1,662
  • 15
  • 16
  • That wouldn't work unless the `DispatcherServlet` took it's configuration from the servlet context (generally) as opposed to the servlet's own configuration (specifically). – Dave Syer Aug 24 '14 at 21:41

2 Answers2

5

With a BeanPostProcessor you can modify a bean after its construction/init phase. You could write a BeanPostProcessor which only modifyes the DispatcherServlet.


public class DispatcherServletConfigurer implements BeanPostProcessor {

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
         if (bean instanceof DispatcherServlet) {
             ((DispatcherServlet) bean).setThrowExceptionIfNoHandlerFound(true);
         }
         return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

Then simply add this as a @Bean to your configuration.

Ian Gilham
  • 1,916
  • 3
  • 20
  • 31
M. Deinum
  • 115,695
  • 22
  • 220
  • 224
0

Try adding a @Bean of type DispatcherServlet and setting whatever properties you need directly.

Dave Syer
  • 56,583
  • 10
  • 155
  • 143
  • Yes, that works. Maybe something to consider to expose as an application property in Spring Boot. Note to others struggling with this: for the setting explained above to have any effect, you would have to turn of some auto config in Spring Boot: `@EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class})` – bep Aug 25 '14 at 00:02
  • Wouldn't it also work with a `BeanPostProcessor` in the case of Spring Boot. – M. Deinum Aug 25 '14 at 12:33
  • Probably a `BeanPostProcessor` would work. (And I'm not sure what the excludes would achieve.) – Dave Syer Aug 25 '14 at 12:34