正常的SpringBoot項目接口,返回對象或者JSON都是正常,但是加入攔截器後,驚奇的發現只能返回String,返回對象就報 “No converter found for return value of type”,解析器無法轉換對象的問題。
網上找了好多解答都是以下幾種:
1、缺失Jackson 依賴,如果有 spring-boot-starter-web依賴可排除該問題
2、是否是 POJO (get set 方法是否有)
註釋:我使用lombok插件,用@Data註解,所以不可能是這個問題導致的。
3、接口是否有@RestController註解
以上的解決方案都不對,罪魁禍首是攔截器的問題!!!
原本攔截器配置使用的是繼承 WebMvcConfigurationSupport導致的。
我原本的攔截器是這樣的:
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
}
WebMvcConfigurationSupport在springMvc源碼中有相關注解
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {}
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class),說明只有當容器中沒有WebMvcConfigurationSupport這個類型的組件的時候,纔會啓動自動配置。
最終我的解決方案是修改攔截器的方式,使用實現WebMvcConfigurer方法。
@Configuration
public class InterceptorConfig implements WebMvcConfigurer{}