What I ended up doing was converting from an implementation of Filter to an implementation of RequestBodyAdvice as outlined below:
@Component
@ControllerAdvice
@RequiredArgsConstructor
@Slf4j
public class RequestSizeAdvice implements RequestBodyAdvice {
@Value("${fam.max_request_size:10485760}")
private int maxContentBytes;
@Override
public boolean supports(MethodParameter methodParameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return inputMessage;
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage,
MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
String bodyString = "";
try {
bodyString = new Gson().toJson(body);
} catch (OutOfMemoryError e) {
throw new MaxSizeExceededException("Unable to calculate body size. Maximum size is %s".formatted(maxContentBytes));
}
long bodySize = bodyString.getBytes().length;
if (bodySize > maxContentBytes) {
throw new MaxSizeExceededException("Body size %s greater than maximum %s".formatted(bodySize, maxContentBytes));
}
return body;
}
@Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage,
MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
}