java - 我想在 RequestBodyAdvice 中使用多个类请求
问题描述
我有这个使用 RequestBodyAdvice 过滤 Question.class 的示例代码。
我的问题是如何使用与 Question.class 几乎相似的多个请求的相同建议。例如我有,Question,Question2,Question3类。他们的大部分属性都非常相似。
@ControllerAdvice
public class CustomRequestBodyAdvice implements RequestBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
System.out.println("In supports() method of " + getClass().getSimpleName());
return methodParameter.getContainingClass() == QuestionController.class && targetType.getTypeName() == Question.class.getTypeName();
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
System.out.println("In beforeBodyRead() method of " + getClass().getSimpleName());
return inputMessage;
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
System.out.println("In afterBodyRead() method of " + getClass().getSimpleName());
if (body instanceof Question) {
Question question = (Question) body;
question.setDate(new Date());
return question;
}
return body;
}
@Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
System.out.println("In handleEmptyBody() method of " + getClass().getSimpleName());
return body;
}
}
解决方案
您可以为所有问题引入一个界面。
public interface QuestionInterface {
void setDate(Date date);
}
在所有问题上实施,而不是具体问题类。
if (body instanceof QuestionInterface ) {
QuestionInterface question = (QuestionInterface) body;
question.setDate(new Date());
return question;
}
对于Type
该类,您可以将其转换为Class
并检测它是否可以从界面分配。
boolean isSupportedClass = false;
if(type instanceof Class) {
Class typeClass = (Class) type;
isSupportedClass = typeClass.isAssignableFrom(QuestionInterface.class);
}
return methodParameter.getContainingClass().equals(QuestionController.class) && isSupportedClass;
推荐阅读
- awk - 模式匹配/排除(awk/sed)
- flutter - 如何在文本选择工具栏中添加新选项
- wordpress -
链接中断代码在function.php(Polylang)中不起作用 - html - 我如何使用引导程序在输入框中添加按钮
- javascript - jQuery 和 HTML,如何在下拉切换菜单中使用本地存储
- time - ffmpeg - 避免生成文件的持续时间近似
- c - C 如何简化这个 For 循环
- asp.net-mvc - 无法使用剃须刀页面在 asp.netcore 中保存下拉列表
- python - 如何从代码中的任何位置访问用户 uid?
- python - 绕过python中的递归限制