Exposing link on collection entity in spring data REST

你离开我真会死。 提交于 2019-12-08 22:22:30

问题


Using spring data REST I have exposed a ProjectRepository that supports listing projects and performing CRUD operations on them. When I go to http://localhost:8080/projects/ I get the list of projects as I expect.

What I am trying to do is add a custom action to the _links section of the JSON response for the Project Collection.

For example, I'd like the call to http://localhost:8080/projects/ to return something like this:

{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/projects/{?page,size,sort}",
      "templated" : true
    },
    "search" : {
      "href" : "http://localhost:8080/projects/search"
    },
    "customAction" : {
       "href" : "http://localhost:8080/projects/customAction"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 0,
    "totalPages" : 0,
    "number" : 0
  }
}

Where customAction is defined in some controller.

I've tried creating the following class:

public class ProjectCollectionResourceProcessor implements ResourceProcessor<Resource<Collection<Project>>> {

    @Override
    public Resource<Collection<Project>> process(Resource<Collection<Project>> listResource) {
        // code to add the links to customAction here
        return listResource;
    }

}

and adding adding the following Bean to my applications configuration:

@Bean
public ProjectCollectionResourceProcessor projectCollectionResourceProcessor() {
    return new ProjectCollectionResourceProcessor();
}

But process(...) doesn't ever seem to get called. What is the correct way to add links to Collections of resources?


回答1:


The collection resources render an instance of Resources<Resource<Project>>, not Resource<Collection<Project>>. So if you change the generic typing in your ResourceProcessor implementation accordingly that should work as you expect it.




回答2:


I had the same issue. What worked for me was:

public class ProjectsResourceProcessor implements ResourceProcessor<PagedResources<Resource<Project>>> {

    private final @NonNull EntityLinks entityLinks;

    @Override
    public PagedResources<Resource<Project>> process(PagedResources<Resource<Project>> pagedResources) {

       ...

        return pagedResources;
    }
}


来源:https://stackoverflow.com/questions/24274127/exposing-link-on-collection-entity-in-spring-data-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!