【发布时间】:2021-08-30 15:11:29
【问题描述】:
我正在使用 Spring Boot 创建一个非常标准的 REST 服务。这部分意味着很多方法将返回结果页面,因此方法的输入将需要页码、页面大小等 - 例如:
@GetMapping(
value = "",
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
ResponseEntity readAll(
@RequestParam("pn") Integer pageNumber,
@RequestParam("ps") Integer pageSize,
@RequestParam("sc") String sortColumn,
@RequestParam("so") String sortOrder
) {
然后在方法本身中,我们将验证参数(例如,确保页面大小
由于这种模式会一遍又一遍地重复,我只想做一个封装所有这些的注释,但我不确定如何将 4 个 RequestParam 变量转换为单个 Pageable 对象,或者如何访问在方法体的注解中创建的对象。
我尝试了一些基本的注释工作,例如
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ServicePageSizeValidator.class)
public @interface ServicePageSize {
Integer DEFAULT_MAX = 100;
String max() default "100";
}
class ServicePageSizeValidator
implements ConstraintValidator<ServicePageSize, Integer> {
private static final Logger LOGGER =
LoggerFactory.getLogger(ServicePageSizeValidator.class);
private Integer max = ServicePageSize.DEFAULT_MAX;
@Override
public void initialize(final ServicePageSize annotation) {
try {
max = Integer.valueOf(annotation.max());
} catch (Exception e) {
LOGGER.warn(
"Exception caught trying to parse page size " +
"constraint {}.", annotation.max(), e
);
max = ServicePageSize.DEFAULT_MAX;
}
}
@Override
public boolean isValid(final Integer pageSize,
final ConstraintValidatorContext context) {
try {
if (pageSize == null) {
throw new InvalidPageSizeException("Null page size.");
}
if (pageSize > max) {
throw new InvalidPageSizeException(
"Page size " + pageSize + "larger than maximum " +
"allowed (" + max + ")."
);
}
} catch (Exception e) {
LOGGER.warn("Invalid page size.", e);
return false;
}
return true;
}
}
这通常似乎有效,但它只对单个参数进行操作,如果参数错误,整个注释就会失败 - 我无法访问有关方法中验证的信息,假设它通过了。
【问题讨论】:
标签: java spring-boot annotations