FeignClient使用问题

479 阅读1分钟

场景: 在SpringMvc中使用@FeignClient会将feignclient中的URL mapping注册到mvc controller中. 可能会出现和已有项目中的url mapping冲突的情况

技术栈: spring boot

解决方案: 

@Configuration
@ConditionalOnClass({Feign.class})
public class FeignConfiguration {

    @Bean
    public WebMvcRegistrations feignWebRegistrations() {
        return new WebMvcRegistrations() {
            @Override
            public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
                return new FeignRequestMappingHandlerMapping();
            }
        };
    }

    private static class FeignRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
        // 解决使用@FeignClient会把client中的URL mapping到项目中的现象,因为我们的client使用了继承会把接口定义中的
        // @Controller或@RequestMapping继承过来
        @Override
        protected boolean isHandler(Class<?> beanType) {
            return super.isHandler(beanType) &&
                    !AnnotatedElementUtils.hasAnnotation(beanType, FeignClient.class);
        }
    }
}