Spring Data REST在运行时选择字段

时间:2019-06-05 07:19:02

标签: java spring spring-data-rest

我在项目中使用Spring Boot,Spring Data REST,Spring HATEOAS。 我的域模型非常复杂,我想遵循REST best practice as the fields selection中的一些知识。

我确实知道Spring projections,但我正在寻找一种方法来告诉我在运行时需要从客户端获取哪些字段。简单地称为GET /cars?fields=manufacturer,model,id,color

由于我想利用Spring Data,我认为我应该在REST调用和Spring之间创建一些东西。 您知道一些类似的好资源/示例吗?

1 个答案:

答案 0 :(得分:4)

使用波形过滤器

@GetMapping(value="cars")
public @ResponseBody List<Car> getCars(@RequestParam("fields") String fields){
List<Car> carList ;
-------
ObjectMapper mapper = = Squiggly.init(new ObjectMapper(), fields);  
System.out.println(SquigglyUtils.stringify(mapper, carList));
-------
}       

更多内容

https://github.com/bohnman/squiggly-java

使用SimpleBeanPropertyFilter

汽车课,

@JsonFilter("myfilter")
public class Car {
    public String color;
    public String model;
    public String type;

在控制器上,

@GetMapping(value = "/cars")
public ResponseEntity<?> getCars(@RequestParam("fields") String fields) throws IOException {
        List<Car> list = Arrays.asList(new Car("pink", "verna", "sedan"), new Car("black", "i10", "hatchback"),
                new Car("voilet", "brizza", "SUV"));
        SimpleFilterProvider  filterProvider = new SimpleFilterProvider().addFilter("myfilter",
                SimpleBeanPropertyFilter.filterOutAllExcept(fields.split(",")));
        ObjectMapper mapper = new ObjectMapper().setFilterProvider(filterProvider);;
        return new ResponseEntity<>(mapper.readValue(mapper.writeValueAsString(list),Object.class), HttpStatus.OK);
    }