0

Say I have registered 2 org.springframework.http.converter.HttpMessageConverter<T> objects:

  1. HttpMessageConverter<Foo> that will convert the HTTP message to an instance of Foo.class and supports Content-Type "application/foo"
  2. HttpMessageConverter<Bar> that will convert the HTTP message to an instance of Bar.class and supports Content-Type "application/bar"

I have the below Rest endpoint that consumes both the above:

@RequestMapping(value = "/foobar", method = POST,
    consumes = {"application/foo", "application/bar"}
public String readFooBar(???){
    ...
}

What parameter definition goes in the "???", is it Foo foo, Bar bar, Object canBeFooOrBar and then downcast in my logic, or something else?

In short, what is the easiest way to deal with 2 separate RequestMapping consumes that generate 2 different objects?

2 Answers 2

1

There is no difference between the controller method, and any other Java method. If a method has one argument, but you want to pass two different object types(Foo, Bar), then these types must share a common super type (and Object does not count, except in very special cases).

Foo and Bar would only share a super type, if the super type has a method (doWork), and the implementation of this method in Foo and Bar contains all the special processing logic (like Runnable). If you need to do instance of in you Controller method, then you should have two Controller methods, because then Foo and Bar are not related. These a general rules for working with polymeric types.

0

Thanks to the nice explanation by Klaus Groenbaek, I solved my problem by doing:

@RequestMapping(value = "/foobar", method = POST,
    consumes = {"application/foo"}
public String readFoo(Foo foo){
    ...
}

@RequestMapping(value = "/foobar", method = POST,
    consumes = {"application/bar"}
public String readBar(Bar bar){
    ...
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.