问题
I would like to add custom rest controller to be added to the json/hal response of the entry point, together with all the respositories that are added by spring. I'm struggling with this by two problems:
How can I add my custom controller so it appears on the entry point together with the links to my repository?
How can I decorate with a link to my custom controller on a representation of an entity produced by the repository so I can link to my custom controller?
I have struggled for a while and created a github project using spring-data-mongodb to demonstrate what I mean. There is one simple Entity Invoice
and the InvoiceRepository
which extends MongoRepository and has one special finder Method List<Invoice> findByFirstName(@Param("firstName")String firstName);
.
In addition there are two custom controller that I would like to be included in the _links
section on the entry point of the service-
Using the Hal Browser, the entry point at the moment looks like
{
"_links": {
"invoices": {
"href": "http://localhost:8080/customize/invoices{?page,size,sort}",
"templated": true
},
"profile": {
"href": "http://localhost:8080/customize/profile"
}
}
}
But I would like it to be
"_links": {
"invoices": {
"href": "http://localhost:8080/customize/invoices{?page,size,sort}",
"templated": true
},
"export": {
"href": "http://localhost:8080/customize/export/invoices"
},
"custom":{
"href": "localhost:8080/customize/invoices/search/customList"
}
"profile": {
"href": "http://localhost:8080/customize/profile"
}
}
To the second part of my question, I have no Idea how to achieve. The JSON representation of an invoice looks like
{
"firstName": "Chuck",
"lastName": "Noris",
"amount": 2.5,
"exported": false,
"_links": {
"self": {
"href": "http://localhost:8080/customize/invoices/27490450945023268364302849904"
},
"invoice": {
"href": "http://localhost:8080/customize/invoices/27490450945023268364302849904"
}
}
}
I would like to extend it with custom export link to each invoice like this
{
"firstName": "Chuck",
"lastName": "Noris",
"amount": 2.5,
"exported": false,
"_links": {
"self": {
"href": "http://localhost:8080/customize/invoices/27490450945023268364302849904"
},
"invoice": {
"href": "http://localhost:8080/customize/invoices/27490450945023268364302849904"
}
"export": {
"href": "http://localhost:8080/customize/export/invoice/27490450945023268364302849904"
}
}
}
回答1:
As commented by Alan the answers are already given on StackOverflow:
Q1
Q2
For other readers I'have updated my Github Project with a sample implementation of both UseCases. Enjoy at spring-data-rest-hal-custom.
来源:https://stackoverflow.com/questions/42972766/how-to-add-custom-links-to-non-repository-rest-controller-in-spring-data-rest-ha