Spring 不同控制器中的引导 REST 映射冲突事件

Spring Boot REST mapping conflict event in different controller

我的 Spring boot(1.4.0 RELEASE) 应用程序中有两个 Rest 控制器:

@RestController("/ctrl")
public class TestController {
    @GetMapping
    public void test() {

    }
}


@RestController("/ctrl2")
public class TestController2 {
    @GetMapping
    public void test() {

    }
}

当我 运行 Spring 启动应用程序时:

Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map '/ctrl2' method 
public void com.xxx.controller.TestController2.test()
to {[],methods=[GET]}: There is already '/ctrl' bean method
public void com.xxx.controller.TestController.test() mapped.

如果我删除一个控制器,一切都很好,应用程序可以正常启动。那么问题出在哪里呢?

您所要做的就是像这样更改您的代码:

@RestController
@RequestMapping("/ctrl")
public class TestController {
    @GetMapping
    public void test() {

    }
}


@RestController
@RequestMapping("/ctrl2")
public class TestController2 {
    @GetMapping
    public void test() {

    }
}

请注意,我已将 RequestMapping 注释添加到控制器。

您在 @RestController 注释中使用的名称与映射无关。它用作将在 Spring 上下文

中注册的 bean 的名称

让我们看看 JavaDoc for @RestController:

value
The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an autodetected component.

因此您声明了一个名为 /ctrl 的控制器 bean 和另一个名为 /ctrl2 的控制器 bean,它们都映射到 /!

您的意思是:

@RestController
@RequestMapping("/ctrl")
public class TestController {
    @GetMapping
    public void test() {

    }
}

来自JavaDoc for @RequestMapping

value
Supported at the type level as well as at the method level! When used at the type level, all method-level mappings inherit this primary mapping, narrowing it for a specific handler method.
emphasis theirs