如何替换已废弃的类方法?基于WebMvcConfigurerAdapter代码场景
修复废弃方法的替代方案
我来帮你把这段代码里的废弃方法替换成当前Spring生态推荐的写法,两个核心废弃点都给你处理妥当:
原代码的问题点
WebMvcConfigurerAdapter在Spring 5及以后版本已被废弃,官方推荐直接实现WebMvcConfigurer接口(该接口现在包含Java 8默认方法,无需强制实现所有方法)new PageRequest(0, 20)的构造方法已废弃,现在应该使用静态工厂方法PageRequest.of()
修改后的完整代码
import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.PageRequest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver(); // 替换废弃的PageRequest构造方法为静态工厂方法 resolver.setFallbackPageable(PageRequest.of(0, 20)); argumentResolvers.add(resolver); // 实现WebMvcConfigurer接口后,无需调用super方法(接口默认方法为空实现) } }
关键修改说明
替换WebMvcConfigurerAdapter为WebMvcConfigurer接口
原本的WebMvcConfigurerAdapter是为了适配旧版接口的抽象类,Spring 5引入Java 8默认方法后,WebMvcConfigurer接口本身已经提供了所有方法的默认空实现,直接实现接口就可以只重写你需要的方法,代码更简洁且符合当前规范。替换PageRequest构造方法为静态工厂方法
PageRequest.of(int page, int size)是Spring Data现在推荐的分页请求实例创建方式,它会自动处理分页索引的合法性检查(比如page不能为负数),比直接调用构造方法更安全、更符合编码规范。
内容的提问来源于stack exchange,提问作者Maciaz
相关产品推荐
相关产品推荐

