最近在使用Feign组合微服务的时候发现在@FeignClient接口类上使用@ReqestMapping无效。
像下面的这个代码:
@FeignClient("xxx")
@RequestMapping("/owner")
public interface OwnerApi{
@RequestMapping("/insert")
public Result add(@RequestBody AzpOwner bean); @RequestMapping("/delete")
public Result delete(Long id); @RequestMapping("/update")
public Result update(@RequestBody AzpOwner bean); @RequestMapping("/findById")
public Result find(Long id);
}
当我们启动服务并调用生产者的时候,报如下的错误:
我一直以为是我的代码有问题,最后发现是SpringMVC和Feign在加载RequestMapping冲突的原因(参考:http://blog.didispace.com/spring-cloud-feignclient-problem/?utm_source=tuicool&utm_medium=referral)
解决方案就是修改SpringMVC的配置让他不映射带有@FeignClient注解的路径,配置类如下:
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.web.WebMvcRegistrations;
import org.springframework.boot.autoconfigure.web.WebMvcRegistrationsAdapter;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import feign.Feign; @Configuration
@ConditionalOnClass({Feign.class})
public class FeignConfiguration {
@Bean
public WebMvcRegistrations feignWebRegistrations() {
return new WebMvcRegistrationsAdapter() {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new FeignRequestMappingHandlerMapping();
}
};
} private static class FeignRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
@Override
protected boolean isHandler(Class<?> beanType) {
return super.isHandler(beanType) &&
!AnnotatedElementUtils.hasAnnotation(beanType, FeignClient.class);
}
}
}
需要注意的小细节是该类需要放到@Application的子包下才能被扫描生效