I have a Spring Boot application and I want to list all Data Repositories and also all the methods for each repository. How could I achieve this?
Asked
Active
Viewed 2,642 times
1 Answers
1
Here is one way of doing so that leverages spring-data-commons
Repositories repositories = new Repositories(context.getBeanFactory());
Iterator it = repositories.iterator();
while(it.hasNext()) {
Class<?> domainClass = (Class<?>) it.next();
//Get Repositories
repositories.getRepositoryFor(domainClass);
//Get Query Methods
List<QueryMethod> methods = repositories.getQueryMethodsFor(domainClass);
}
Note: The above code only fetches the automatically implemented Spring Data Query methods. If you need all Query methods including those from the provided interfaces (e.g. CrudRepository) as well as custom Query method implementations then use the following:
Repositories repositories = new Repositories(context.getBeanFactory());
Iterator it = repositories.iterator();
while(it.hasNext()) {
Class<?> domainClass = (Class<?>) it.next();
Advised repoProxy = (Advised)repositories.getRepositoryFor(domainClass);
Class<?>[] interfaces = repoProxy.getProxiedInterfaces();
List<Method> methods = Arrays.stream(interfaces)
.flatMap(c -> Arrays.stream(ReflectionUtils.getAllDeclaredMethods(c)))
.collect(toList());
}

Kyle Anderson
- 6,801
- 1
- 29
- 41
-
1Thanks @KyleAnderson that's exactly what I was looking for! – Jose Romero Sep 20 '17 at 19:28
-
getQueryMethodsFor() doesn't return query methods from custom repositories (https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations) . How could I get this methods? – Jose Romero Sep 21 '17 at 17:38
-
@JoseRomero I've added another option to my answer which satisfies your requirement. – Kyle Anderson Sep 21 '17 at 22:59
-
@KyleAnderson I need to have a list of all repositories. How can I make it by using this class? You can find more details about my use case [here](https://stackoverflow.com/questions/62194634/spring-boot-get-a-list-of-repositories-in-non-runner-classes). I have a class that all my repositories extended that. I need something like `List
repositories` . – MJBZA Jun 04 '20 at 13:18 -
where is the context coming from? is this a variable? – Markos Tzetzis Oct 25 '21 at 06:05