springcloud包扫描feign和controller冲突

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 )
            );
        }
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值