共计 2212 个字符,预计需要花费 6 分钟才能阅读完成。
应用 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,造成了抵触。
解决办法就是本人定义一个 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());
};
}
}
正文完