Ambiguous mapping. Cannot map ‘xxx‘ method 启动异常解决

2024-01-03 09:38:55

问题描述

问题代码展示:

@SpringBootApplication
@ComponentScan(nameGenerator = QueryAllCityAnnotationBeanNameGenerator.class)
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

@RestController
@RequestMapping("/getAllCity")
public class TitysAction {
    @RequestMapping("/citys")
    public List<City> citys(){
        return "业务逻辑";
    }
}

启动异常:

Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'titysAction' method 
org.example.action.TitysAction#citys()
to { [/getAllCity/citys]}: There is already 'org.example.action.TitysAction' bean method
org.example.action.TitysAction#citys() mapped.

问题解决

原因:@SpringBootApplication已经包含了@ComponentScan,默认就会扫描当前包,及其子包下的组件。 上述代码又定义了一个 @ComponentScan扫描了QueryAllCityAnnotationBeanNameGenerator类所在的包。 这两次扫描,都加载了同一个Controller,所以导致映射冲突。

代码修改如下:

@SpringBootApplication(nameGenerator = QueryAllCityAnnotationBeanNameGenerator.class) 
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

@RestController
@RequestMapping("/getAllCity")
public class TitysAction {
    @RequestMapping("/citys")
    public List<City> citys(){
        return "业务逻辑";
    }
}

文章来源:https://blog.csdn.net/zhengzhaoyang122/article/details/135352249
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。