Reputation: 1135
For example, here's a method which returns a User
:
@RequestMapping(method = GET, value = "/user")
public User getUser() {
return new Users();
}
For some reasons, the client expect an other type
class CommonResponse<T> {
int code;
T data;
}
So I need to convert all return value from T
(User
for this e.g.) to CommonResponse<T>
before it handled by the MessageConverter
.
Cause there're many request hanlders should be modified, is there any way to write the convert data just once?
Upvotes: 3
Views: 2346
Reputation: 1135
Finally I find ResponseBodyAdvice to do such work.
Here the sample code:
@RestControllerAdvice
public class CommonAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return returnType.getDeclaringClass().getPackage().getName().startsWith("foo.bar.demo");
// you can change here to your logic
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
return new CommonResponse<Object>().setCode(200).setData(body);
}
}
Upvotes: 2
Reputation: 11027
you need to add/configure your custom converter. so that your custom converter is executed before others
@EnableWebMvc
@Configuration
@ComponentScan({ "org.app.web" })
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
messageConverters.add(createCustomConverter());
super.configureMessageConverters(converters);
}
private HttpMessageConverter<Object> createCustomConverter() {
....
}
}
Upvotes: 1