Environment:
-
Spring Version 5.2.6
-
JDK1.8
Question:
The parameters from the front end POST request are like this{"data": {"a": 1, "b": "hello"}}
.
I hope the following two methods can be used to automatically bind parameters.
- Map
hello(Integer a, String b){} - Map
hello(ParamVo vo){}
The ParamVo like this
class ParamVo{ Integer a; String b; }
To do this,We need to take the data from the JSON object and assign values to the method parameters. My approach:
-
I declare a annotation like this
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @RestController public @interface DataRestController { }
-
I declare a class implement by HandlerMethodArgumentResolver,like this:
public class DataRestControllerArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.getDeclaringClass().getAnnotation(DataRestController.class) != null; } }
The purpose of doing this is to realize my purpose in the method resolveargument, and take the data from the JSON object for parameter binding.Because spring MVC can only directly take data from JSON object for binding.
But unfortunately, When my controller method Usage 1 like this Map<String, Object> hello(Integer a, String b){}
.
The class RequestParamMethodArgumentResolver managed parameter resolution.Spring MVC will not use my custom class DataRestControllerArgumentResolver .
So what should I do?
I think a solution, The RequestMappingHandlerAdapter#getDefaultArgumentResolvers
, use an ordered list and load the customer's HandlerMethodArgumentResolver
first.
Comment From: rstoyanchev
Thanks for getting in touch, but it feels like this is a question that would be better suited to Stack Overflow. As mentioned in the guidelines for contributing, we prefer to use the issue tracker only for bugs and enhancements. Feel free to update this issue with a link to the re-posted question (so that other people can find it) or add some more details if you feel this is a genuine bug.