没有为接口 org.springframework.data.domain.Pageable 找到主构造函数或默认构造函数

2022-09-01 22:42:23

我试图在我的RestController中实现Pageable,并遇到了以下错误消息“没有为接口org.springframework.data.domain.Pageable找到主构造函数或默认构造函数”的问题。

我的控制器是

@GetMapping("/rest/category/all/page")
public Page<ItemCategory> getAllItemCategoryByPage(Pageable pageable){
    Page<ItemCategory> categories = itemCategoryService.getAllItemCategoriesByPageable(pageable);
    return categories;
}

我在这里做错了什么。这是一个Spring Boot 2.0应用程序。提前致谢!


答案 1

所选解决方案是一种解决方法。您可以使用以下配置使Spring自动解析参数:

import org.springframework.context.annotation.Configuration;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@EnableSpringDataWebSupport
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add( new PageableHandlerMethodArgumentResolver());
    }
}

答案 2

如果您使用 Clément Poissonnier 的解决方案请检查一个配置类是否不覆盖另一个配置类

我遇到了同样的问题,下面的解决方案无法解决它:

@Configuration
@EnableSpringDataWebSupport
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add( new PageableHandlerMethodArgumentResolver());
    }
}

我仍然收到消息:

没有为接口 org.springframework.data.domain.Pageable 找到主构造函数或默认构造函数

然后我意识到这个项目有一个Swagger配置类

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebMvcConfigurationSupport {
    // Swagger configuration...
}

并且上述 WebMvcConfig 配置被忽略

解决方案是只有一个配置类:

@Configuration
@EnableSwagger2
public class WebMvcConfig extends WebMvcConfigurationSupport {
    // Swagger configuration...

    @Override
        public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
            argumentResolvers.add( new PageableHandlerMethodArgumentResolver());
        }
    }
}

你可能也不需要像约翰·保罗·摩尔(John Paul Moore)的回答所指出的那样@EnableSpringDataWebSupport


推荐