文章目录
问题描述
在做项目的时候,运行时,无意中遇到了这个问题,Ambiguous mapping. Cannot map ‘/test’ method,大概意思就是===》模糊映射。无法映射’/test’方法.
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 ‘/test’ method
com.example.controller.TestController#test1()
to {GET []}: There is already ‘/test’ bean method
com.example.controller.TestController#test2() mapped.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.26.jar:5.3.26]
…
Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘/test’ method
com.example.controller.TestController#test1()
to {GET []}: There is already ‘/test’ bean method
com.example.controller.TestController#test2() mapped
…
环境:SpringBoot2.7.10 + jdk,是一个简单的SpringBoot的web案例,maven依赖如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.10</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>javatest2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>javatest2</name>
<description>javatest2</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
出现上面那个问题的原因
从报错信息(Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘/test’ method)模糊映射。无法映射’/test’方法.。大概就可以知道,造成这个的原因就是对应的接口方法映射不唯一。具体原因如下所示
稍微改一下就好了,如下图所示
下面这样也是可以的
同理,下面这样肯定也是不行的,同样也是报一样的错误
Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘/test’ method
com.example.controller.TestController#test2(Long)
to {GET [/aaa]}: There is already ‘/test’ bean method
除了上面那个错误,还有一个错误是项目启动的时候并不报错,但是请求发送请求的时候就报错了。而且报的还是同样的错误
也是映射模糊的报错,这个跟上面一样的报错,只不过,这个是发送请求的时候才报错。而上面那一个是启动项目的时候就报错了。
具体看这里:springboot中报错java.lang.IllegalStateException: Ambiguous handler methods mapped for-优快云博客