1、springcloud项目如果包扫描同时扫描到了feign接口和controller会报错
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'com.peppa.tmp.employee.intf.EmployeeFeign' method
public abstract com.peppa.tmp.common.Response<com.peppa.tmp.employee.vo.EmployeeVo> com.peppa.tmp.employee.intf.EmployeeFeign.employByEmail(java.lang.String)
to {[/employee/employByEmail],methods=[GET]}: There is already 'employeeController' bean method
解决办法
在Spring Boot里,有一个WebMvcAutoConfiguration类专门加初始化spring mvc 需要的bean,里面有一个内部类,也是打上@Configuration注解的:
直接重写这个getRequestMappingHandlerMapping的实现就可以了,所以注入这个Bean:
package com.peppa.tmp.conf;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
/**
* @program: peppa-tmp
* @description:
* @author: zhoupengfei
* @create: 2019-09-19 15:54
**/
//@Configuration
public class WebMvcRegistrationAdpater implements WebMvcRegistrations {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new MyRequestMappingHandlerMapping();
}
public class MyRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
@Override
protected boolean isHandler(Class<?> beanType) {
// 原来逻辑:
/*
return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
*/
//去掉RequestMapping
return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
( AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class) && beanType.isInterface()==false )
);
}
}
}