gpt4 book ai didi

Java-Controller引起的Ambiguous mapping问题解决

转载 作者:知者 更新时间:2024-03-13 03:34:10 27 4
gpt4 key购买 nike

问题描述

出现java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'xxx' method异常。

通过上面代码我们可以看出来当spring添加Controller的接口Mapping的时候会先进行效验,如果以存在相同的Mapping了,并且方法来源不是同一个类,那么就会报错

比如:

  1. 子类继承父类的Controller的方法,url都一样
  2. 两个不同类的Controller内的方法url地址都一样,但是方法行为都不同(名称.参数,返回值…)
    总结: 只要出现相同的url接口就会报错

解决办法

  1. 重写RequestMappingHandlerMapping的getMappingForMethod方法。
  2. 判断是准备注册的Mapping是否以存在
  3. 如果存在那么就将原来的Mapping删除使用现在的Mapping

代码

//解决重写Controller, 方法参数返回值不一致的问题,
//解决办法就是如果子类中有相同路径的url接口那么就不映射父类的url接口了
public class PathTweakingRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
//handlerType.equals(ParentclassController.class) || handlerType.equals(SubclassController.class)
    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        RequestMappingInfo methodMapping = super.getMappingForMethod(method, handlerType);
        if (methodMapping==null) {
            return methodMapping;
        }

        Map<RequestMappingInfo, HandlerMethod> handlerMethods = super.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> requestMappingInfoHandlerMethodEntry : handlerMethods.entrySet()) {
            for (String pattern : requestMappingInfoHandlerMethodEntry.getKey().getPatternsCondition().getPatterns()) {
                for (String s : methodMapping.getPatternsCondition().getPatterns()) {
                    if (pattern.equals(s)) {    //发现有重复的
                        //删除原来的
                        super.unregisterMapping(requestMappingInfoHandlerMethodEntry.getKey());
                        return null;
                    }
                }
            }
        }

        return methodMapping;
    }
}
package com.schemautils.config;

import com.schemautils.PathTweakingRequestMappingHandlerMapping;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebMvcRegistrationsConfig  implements WebMvcRegistrations {
    @Override
    public PathTweakingRequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return new PathTweakingRequestMappingHandlerMapping();
    }
}

点赞 -收藏-关注-便于以后复习和收到最新内容有其他问题在评论区讨论-或者私信我-收到会在第一时间回复如有侵权,请私信联系我感谢,配合,希望我的努力对你有帮助^_^

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com