Error creating bean with name ‘requestMappingHandlerMapping’ spring boot

What is the issue?

In our spring boot application on controller level when we added same request mapping for multiple methods, we got into this issue. Following is the issue in details:

The error message

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 'springController' method 
public java.lang.String no.mentormedier.migration.controller.SpringController.home(org.springframework.ui.Model)
to { /}: There is already 'homePageController' bean method

How to get the error?

In spring request mapping it is not allowed to have same URL map on multiple methods. The @RequestMapping annotation will simply not allow us to do that. The following code will run into this error:

    @RequestMapping({"/"})
    public String home(Model model) {
        model.addAttribute("targetEnv", activeProfile);
        return "home";
    }

    @RequestMapping({"/"})
    public String newhome(Model model) {
        model.addAttribute("targetEnv", activeProfile);
        return "newhome";
    }

The solution

We will have to have different request mapping for different methods. We can simply change the request mapping with something unique and that will solve this issue:

    @RequestMapping({"/"})
    public String home(Model model) {
        model.addAttribute("targetEnv", activeProfile);
        return "home";
    }

    @RequestMapping({"/new"})
    public String newhome(Model model) {
        model.addAttribute("targetEnv", activeProfile);
        return "newhome";
    }
Share