Search code examples
spring-bootspring-data

Is it possible to create a fully custom Repository for Spring Data?


I am looking to create a fully custom Spring Data CrudRepository which would be backed by an external API service. Is this possible in the current Spring Data set-up?

Alternatively, should I look to wire-up my own solution with the standard Mvc or WebFlux controllers + service calls?

All my research points to requiring a standard database or dialect such as SQL, Redis, etc., rather than a fully custom Repository.

— EDIT: Adding more explanation on the ‘why’.

The Spring Data REST framework provides a range of nice, opinionated, ready-to-use solutions for making a backing repository behaviour more like a web service. I was hoping to tap into this by building a customised @CrudRepository that swaps the SQL queries for custom API calls.

Spring Data REST does not appear to pick up the @CrudRepository classes if a backing data source (as evidenced by a doc type, i.e. @Entity or @RedisHash) is not in the class path.

The alternative is to go for the ‘traditional’ @Controller -> @Service -> @Repository route is likely the simpler option.


Solution

  • You could create a repository implementation class by following: https://www.baeldung.com/spring-data-composable-repositories

    And have it not perform database queries but instead call out to an external API instead via RestTemplate (Spring Mvc) or WebClient (Spring Webflux)

    However I wouldn't recommend this, it sounds like a peculiar thing to do. Instead I would create a Service (class annotated with @Service) that is responsible for calling out to this external API.