我很想知道Spring Boot
如何在控制器方法中与Pageable
一起工作?我添加了一个可分页参数到我的控制器方法,Spring为我处理它。
有一个例子:
@GetMapping("search")
public ResponseEntity<List<ProductDTO>> searchProducts(
@RequestParam(value = "query", required = false, defaultValue = "") String query,
Pageable pageable) {
Specification<Product> spec = Specification.where(null);
if(!StringUtils.isBlank(query)) {
Node rootNode = new RSQLParser().parse(query);
spec = rootNode.accept(new CustomRsqlVisitor<Product>());
}
Page<ProductDTO> page = service.searchProducts(spec, pageable);
// My Additional code....
}
现在让我们回到主要问题:Spring如何处理Pageable?那么,我如何为自己创建相同的业务来处理输入法规范呢?
注:1:我使用rsql-parser来实现对我的产品的搜索。
注:2:你可以在rsql包
下找到用来生成Specification的自定义类您可以通过实现自定义HandlerMethodArgumentResolver
来实现这一点。
创建HandlerMethodArgumentResolver
:
@Component
public class CustomClassMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterType().equals(CustomClass.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
// You can get the values you need from the request and convert it to a new object.
// Example: String requestPathInfo = nativeWebRequest.getRequest().getPathInfo();
// Example: String headerUrl = nativeWebRequest.getHeader("X-Url");
return new CustomClass(/*...*/);
}
}
注册HandlerMethodArgumentResolver
:
你可以让我们的CustomClassMethodArgumentResolver
知道Spring Boot。
@Configuration
public class WebConfig implements WebMvcConfigurer {
//...
@Override
public void addArgumentResolvers(
List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new CustomClassMethodArgumentResolver());
}
}
你可以查看pageablehandlermethoargumentresolver# resolveArgument它调用PageableHandlerMethodArgumentResolverSupport#getPageable
https://github.com/spring-projects/spring-data-commons/blob/main/src/main/java/org/springframework/data/web/PageableHandlerMethodArgumentResolver.java
https://github.com/spring-projects/spring-data-commons/blob/main/src/main/java/org/springframework/data/web/PageableHandlerMethodArgumentResolverSupport.java