Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

hateoas - Exposing link on collection entity in spring data REST

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...