如何修改Spring Pageable默认最大页容量限制?
我有一个包含Specification和Pageable参数的控制器,正常分页查询数据库数据时一切正常,每页返回20条数据,示例响应如下:
............ "totalElements": 2612, "totalPages": 131, "last": false, "size": 20, "number": 0,
但我需要一次性获取全部数据,比如当totalElements为2612时,希望直接拿到所有2612条数据。已知Spring默认最大页容量(max-page-size)为2000,因此我发起了如下请求:
http://localhost:7038/api/get-journal/2c9a508179b2933a0179b2be69fd0003?yearReg=2023&page=0&size=2612
得到的响应却是:
"totalElements": 2612, "totalPages": 2, "last": false, "size": 2000,
可以看到返回的size被限制为2000,数据被分成了两页,和预期不符。
我尝试过网上的解决方案,包括创建配置类,或者在app.properties中添加配置:spring.data.web.pageable.max-page-size=10000,但都没有效果。我使用的是Spring Boot 2.3.3版本。
补充说明
我的REST控制器中,参数值已经被修改:
针对Spring Boot 2.3.3版本中max-page-size配置不生效的问题,可尝试以下方案:
1. 自定义分页参数解析器
创建WebMvc配置类,手动配置PageableHandlerMethodArgumentResolver并设置最大页容量:
import org.springframework.context.annotation.Configuration; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CustomWebMvcConfig implements WebMvcConfigurer { @Override public void addArgumentResolvers(java.util.List<HandlerMethodArgumentResolver> resolvers) { PageableHandlerMethodArgumentResolver pageableResolver = new PageableHandlerMethodArgumentResolver(); // 设置最大页容量为10000 pageableResolver.setMaxPageSize(10000); resolvers.add(pageableResolver); } }
2. 确认配置属性正确生效
检查application.properties(或application.yml)中的配置是否正确,Spring Boot 2.x版本的分页配置格式如下:
# application.properties spring.data.web.pageable.max-page-size=10000 spring.data.web.pageable.default-page-size=20
若使用yml格式:
# application.yml spring: data: web: pageable: max-page-size: 10000 default-page-size: 20
配置完成后重启应用,确保配置被加载。
3. 新增接口直接返回全部数据
如果仅特定场景需要全量数据,可新增一个不使用Pageable的接口,直接调用Repository的全量查询方法:
@GetMapping("/get-journal/all/{id}") public ResponseEntity<List<Journal>> getAllJournals(@PathVariable String id, @RequestParam Integer yearReg) { // 构建你的查询Specification Specification<Journal> spec = Specification.where(...); List<Journal> allJournals = journalRepository.findAll(spec); return ResponseEntity.ok(allJournals); }
4. 排查配置冲突
若项目中存在多个WebMvcConfigurer实现类,可能导致配置被覆盖。可在自定义的配置类上添加@Primary注解,提升其优先级,确保分页配置生效。
内容的提问来源于stack exchange,提问作者Vitaliy

