spring|spring data jpa 分页下标改成1不生效问题排查

使用spring data jpa查询数据分页,默认spring的分页下标page从0开始,而前端对接一般都是从第1页开始,其中有个配置spring.data.web.pageable.one-indexed-parameters,默认为false,即从下标0开始,改成true即为1开始。但是改了之后并没有效果,进行了排查,问题记录如下:
版本 Spring boot version - 2.6.4
原因是使用@EnableSpringDataWebSupport注解,其中默认会加载SpringDataWebConfiguration.class配置类的配置,里面定义了一个bean

@Bean public PageableHandlerMethodArgumentResolver pageableResolver() { PageableHandlerMethodArgumentResolver pageableResolver = new PageableHandlerMethodArgumentResolver(sortResolver.get()); customizePageableResolver(pageableResolver); return pageableResolver; }

而上面那个spring.data.web.pageable.one-indexed-parameters的配置是在自动注入的SpringDataWebAutoConfiguration.class里使用到的
@Bean @ConditionalOnMissingBean public PageableHandlerMethodArgumentResolverCustomizer pageableCustomizer() { return (resolver) -> { Pageable pageable = this.properties.getPageable(); resolver.setPageParameterName(pageable.getPageParameter()); resolver.setSizeParameterName(pageable.getSizeParameter()); resolver.setOneIndexedParameters(pageable.isOneIndexedParameters()); resolver.setPrefix(pageable.getPrefix()); resolver.setQualifierDelimiter(pageable.getQualifierDelimiter()); resolver.setFallbackPageable(PageRequest.of(0, pageable.getDefaultPageSize())); resolver.setMaxPageSize(pageable.getMaxPageSize()); }; }

然后SpringDataWebAutoConfiguration.class这个自动配置类上有个@ConditionalOnMissingBean(PageableHandlerMethodArgumentResolver.class),如果存在了这个bean,则不会自动加载,而SpringDataWebConfiguration类里就有定义了这个bean,形成了冲突。
【spring|spring data jpa 分页下标改成1不生效问题排查】解决办法就是自己定义一个config,其中在定义一个PageableHandlerMethodArgumentResolverCustomizer的bean
@Configuration @EnableConfigurationProperties(SpringDataWebProperties.class) public class Config {@Bean @ConditionalOnMissingBean public PageableHandlerMethodArgumentResolverCustomizer pageableCustomizer(SpringDataWebProperties properties) { return (resolver) -> { Pageable pageable = properties.getPageable(); resolver.setPageParameterName(pageable.getPageParameter()); resolver.setSizeParameterName(pageable.getSizeParameter()); resolver.setOneIndexedParameters(pageable.isOneIndexedParameters()); resolver.setPrefix(pageable.getPrefix()); resolver.setQualifierDelimiter(pageable.getQualifierDelimiter()); resolver.setFallbackPageable(PageRequest.of(0, pageable.getDefaultPageSize())); resolver.setMaxPageSize(pageable.getMaxPageSize()); }; }}

    推荐阅读