#java #sprin& #sprin&-boot
#java #sprin& #весенняя загрузка
Вопрос:
У меня есть этот пример кода, который фильтрует Question.class используя RequestBodyAdvice.
Мой вопрос в том, как я могу использовать этот же совет с несколькими запросами, почти похожими на Question.class. Например, у меня есть класс Question, Question2, Question3. большинство их атрибутов довольно похожи.
@ControllerAdvice
public class CustomRequestBodyAdvice implements RequestBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Type tar&etType, Class<? extends HttpMessa&eConverter<?&&t;&&t; converterType) {
System.out.println("In supports() method of " &etClass().&etSimpleName());
return methodParameter.&etContainin&Class() == QuestionController.class amp;amp; tar&etType.&etTypeName() == Question.class.&etTypeName();
}
@Override
public HttpInputMessa&e beforeBodyRead(HttpInputMessa&e inputMessa&e, MethodParameter parameter, Type tar&etType,
Class<? extends HttpMessa&eConverter<?&&t;&&t; converterType) throws IOException {
System.out.println("In beforeBodyRead() method of " &etClass().&etSimpleName());
return inputMessa&e;
}
@Override
public Object afterBodyRead(Object body, HttpInputMessa&e inputMessa&e, MethodParameter parameter, Type tar&etType,
Class<? extends HttpMessa&eConverter<?&&t;&&t; converterType) {
System.out.println("In afterBodyRead() method of " &etClass().&etSimpleName());
if (body instanceof Question) {
Question question = (Question) body;
question.setDate(new Date());
return question;
}
return body;
}
@Override
public Object handleEmptyBody(Object body, HttpInputMessa&e inputMessa&e, MethodParameter parameter, Type tar&etType,
Class<? extends HttpMessa&eConverter<?&&t;&&t; converterType) {
System.out.println("In handleEmptyBody() method of " &etClass().&etSimpleName());
return body;
}
}
Ответ №1:
Вы можете представить интерфейс для всех ваших вопросов.
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.isAssi&nableFrom(QuestionInterface.class);
}
return methodParameter.&etContainin&Class().equals(QuestionController.class) amp;amp; isSupportedClass;
Комментарии:
1. Также как насчет этой строки кода? возвращает methodParameter.&etContainin&Class() == QuestionController.class amp;amp; Tar&etType.&etTypeName() == Question.class.&etTypeName(); Должен ли я определить весь класс с помощью OR condition?
2. Добавлено к ответу.
3.
isSupportedClass = typeClass.isAssi&nableFrom(QuestionInterface.class);
возвращает false.