SpringBoot @RestController,发现模糊映射

SpringBoot @RestController, Ambiguous mapping found

您好,我的示例中有一个简单的 RestController:

@RestController
public class PersonController {

    @RequestMapping(name = "/getName", method = GET)
    public String getName() {
        return "MyName";
    }

    @RequestMapping(name = "/getNumber", method = GET)
    public Double getNumber(){
        return new Double(0.0);
    }
}

我有用于启动 SpringBoot 的 SampleController:

@SpringBootApplication
@Controller
public class SampleController {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

当我尝试 运行 SampleCotroller 时发生以下异常:

Caused by: java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'personController' bean method 
public java.lang.Double com.web.communication.PersonController.getNumber()
to {[],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'personController' bean method
public java.lang.String com.web.communication.PersonController.getName() mapped.

请问问题出在哪里?一个RestController里不能有多个RequestMapping吗?

非常感谢回复

您必须使用 value 属性来定义映射。您现在已经使用了 name,它只是为映射提供了一个名称,但根本没有定义任何映射。因此,目前您的两种方法都未映射(在这种情况下,两者都映射到同一路径)。将方法更改为:

@RequestMapping(value = "/getName", method = GET)
public String getName() {
    return "MyName";
}

@RequestMapping(value = "/getNumber", method = GET)
public Double getNumber(){
    return new Double(0.0);
}

或者您可以使用,

@GetMapping("/getName")

method with value 用法相同,新版本指定method ="POST" with request mapping value.

RequestMapping(value="/name") 中始终使用路径值而不是名称。 您也可以明智地使用方法,例如 GETMapping("/getname") PostMapping("/addname")