I want to use RestResource annotation of spring data rest. As you know it exposes ALL CRUD methods by default. But I only need findAll method. One way is to set exported value of all other methods to false like this:
@RestResource(path="questions")
public interface QuestionRepository extends CRUDRepository<Question,Long> {
@RestResource(exported = false)
void delete(Long id);
@RestResource(exported = false)
void create(Question q);
....
}
But I don't like this. Is there any other simpler way so I can avoid this metallurgy?
You can achieve this by defining an intermediate generic interface which implements Repository, and expose, for example, all PagingAndSortingRepository methods annotated with
With the help of that source : https://spring.io/blog/2011/07/27/fine-tuning-spring-data-repositories/, here's my solution :
First of all, set the RepositoryDetectionStrategy to ANNOTATED so the only repositories exposed are those annotated @RepositoryRestResource. This can be done with :
Define your generic Rest repository. It has to implement only Repository interface, which is empty, and not CrudRepository or PagingAndSortingRepository, so you can control exactly which methods will be exposed, and the methods exposed doesn't depends on the Spring Data version you're using, or will use.
To garantee the non-exposition you have to annotate with @RestResource(exported=false) each method. It's a bit annoying but done once for all (you can just copy-paste, I take all te methods define in CrudRepository and PagingAndSorting) :
Then, just extends your custom intermediate repository in your final repositories, and override uniquely the method you want to expose, with your example (you get auto-completion so it's quickly done) :
A parameter to set the default value of exported to false would be prefered, but until this is possible, here is the only safe way I find.
You should implement a custom controller for
GET /questions
request that will return only the result offindAll
method, for example:and disable your QuestionRepository to be exported:
Working example.
There is an easy and standard solution and I tried and found it working in spring boot 2.0.2 Write a configuration class as shown below and setExposeRepositoryMethodsByDefault(false) and it's done :)