Spring Boot替换内置的PageableHandlerMethodArgumentResolver

时间:2018-09-14 08:05:23

标签: spring spring-boot

上下文

我在Spring Boot项目中工作。

我想用自定义变量替换内置的PageableHandlerMethodArgumentResolver。

我阅读了spring源代码,并找到了实现该目标的类。

/**
 * Extension of {@link AbstractHandlerMethodAdapter} that supports
 * {@link RequestMapping} annotated {@code HandlerMethod}s.
 *
 * <p>Support for custom argument and return value types can be added via
 * {@link #setCustomArgumentResolvers} and {@link #setCustomReturnValueHandlers},
 * or alternatively, to re-configure all argument and return value types,
 * use {@link #setArgumentResolvers} and {@link #setReturnValueHandlers}.
 *
 * @author Rossen Stoyanchev
 * @author Juergen Hoeller
 * @since 3.1
 * @see HandlerMethodArgumentResolver
 * @see HandlerMethodReturnValueHandler
 */
public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter
    implements BeanFactoryAware, InitializingBean{

    ...

    /**
     * Configure the complete list of supported argument types thus overriding
     * the resolvers that would otherwise be configured by default.
     */
    public void setArgumentResolvers(@Nullable List<HandlerMethodArgumentResolver> argumentResolvers) {
        if (argumentResolvers == null) {
            this.argumentResolvers = null;
        }
        else {
            this.argumentResolvers = new HandlerMethodArgumentResolverComposite();
            this.argumentResolvers.addResolvers(argumentResolvers);
        }
    }

    /**
     * Return the configured argument resolvers, or possibly {@code null} if
     * not initialized yet via {@link #afterPropertiesSet()}.
     */
    @Nullable
    public List<HandlerMethodArgumentResolver> getArgumentResolvers() {
        return (this.argumentResolvers != null ? this.argumentResolvers.getResolvers() : null);
    }

    ...

}

因此,我这样替换内置的PageableHandlerMethodArgumentResolver。

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private RequestMappingHandlerAdapter adapter;

    @PostConstruct
    public void replacePageableHandlerMethodArgumentResolver(){
        //remove the built-in PageableHandlerMethodArgumentResolver
        List<HandlerMethodArgumentResolver> argumentResolvers = adapter.getArgumentResolvers().stream()
            .filter(argumentResolver -> !(argumentResolver instanceof PageableHandlerMethodArgumentResolver))
            .collect(Collectors.toList());

        //add my custom PageableHandlerMethodArgumentResolver
        argumentResolvers.add(new PageableHandlerMethodArgumentResolver(new CicdSortHandlerMethodArgumentResolver()));

        //re-configure all arguments
        adapter.setArgumentResolvers(argumentResolvers);
    }
}

问题

我运行代码并获得以下异常:

java.lang.IllegalStateException: No primary or default constructor found for interface org.springframework.data.domain.Pageable

我猜内置的PageableHandlerMethodArgumentResolver已成功删除,但是为什么我的自定义PageableHandlerMethodArgumentResolver不起作用?

0 个答案:

没有答案