首页 > 解决方案 > 我想在 RequestBodyAdvice 中使用多个类请求

问题描述

我有这个使用 RequestBodyAdvice 过滤 Question.class 的示例代码。

我的问题是如何使用与 Question.class 几乎相似的多个请求的相同建议。例如我有,QuestionQuestion2Question3类。他们的大部分属性都非常相似。

@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;
    }
}

标签: javaspringspring-boot

解决方案


您可以为所有问题引入一个界面。

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;

推荐阅读