SpringBoot配置拦截器时,始终报错:
cannot be cast to org.springframework.web.accept.ContentNegotiationManager
启动入口:
@EnableAutoConfiguration @SpringBootApplication @ImportResource("classpath:application-mvc.xml") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) { ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet); registration.addUrlMappings("*.do", "*.go"); return registration; } }
Interceptor:
public class CustomSSOSpringInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } }
配置拦截器:
@Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new CustomSSOSpringInterceptor()).addPathPatterns("/**"); } }
没有问题啊?可是始终报错,网上找了很多资料,都没有一个具体的说法,最后在一个小回复里看到了报错的原因:
I finally found the error, I was including a xml-config with <mvc:annotation-driven/>... I removed this, now it works
原来是我在application.xml文件里面配置了如下东西:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"
default-autowire="byName">
<mvc:annotation-driven/>
<bean class="com.ahoi.demo.common.interceptor.ControllerClassNameHandlerMapping"></bean>
</beans>
注释掉就可以了!