Issue
I am trying to overload a @RestController
class's method which has the same exact endpoint (url).
However, when I do, I get the following error:
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 'helloWorldController' method com.rest.webservices.restfulwebservices.helloworld.HelloWorldController#helloWorldInternationalized(Locale) to {GET [/hello-world-internationalized]}: There is already 'helloWorldController' bean method
If I change the endpoint (url) to something else, error goes away. In the code below, you can see I use the "hello-world-internationalized"
string as endpoint value for both methods which gives me an error about the bean method.
@RestController
public class HelloWorldController {
@Autowired
private MessageSource messageSource;
@GetMapping(path="/hello-world-internationalized")
public String helloWorldInternationalized(@RequestHeader(name="Accept-Language", required=false) Locale locale) {
return messageSource.getMessage("good.morning.message", null, locale);
}
//other version of the method
@GetMapping(path="/hello-world-internationalized")
public String helloWorldInternationalizedVersion2() {
return messageSource.getMessage("good.morning.message", null, LocaleContextHolder.getLocale());
}
}
In Spring Boot @RestController
class, is it not possible to overload a method and use the same url for both?
I'd appreciate any comment. Your comments will help me understand this scenario better.
Thank you.
Solution
Yes and no. What you currently have is 2 get methods mapped to the same URL, there is no differentiator in the mapping for Spring to determine which one to use when a request comes in.
As you are using a request header in your second one, you could use the headers
element on the @GetMapping
to add an additional mapping info.
@GetMapping(path="/hello-world-internationalized", headers="Accept-Language")
Now if that specific header is present the method will now be called.
It is important that the mapping information (or metadata) needs to be unique for each method, if the information is the same you will get an error.
Answered By - M. Deinum
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.