Given the list of all spring data repositories in some class Bar
:
@Autowired
private List<Repository> repositories;
How can I find the repository for an existing domain class Foo
in the above list?
Assuming that the following exists:
@Entity
public class Foo {
...
}
and
public interface FooRepository extends JpaRepository<Foo, String> {}
The key to the solution is Spring's
org.springframework.data.repository.core.support.DefaultRepositoryMetadata
which provides the methodgetDomainType()
.DefaultRepositoryMetadata
needs the repository interface as constructor arg. So one can loop over all existing repositories, retrieve the repository interface (which is still a tricky part because the repository instance has more than one interface) and find the one wheregetDomainType()
equalsFoo.class
.Spring Data Commons contains a class
Repositories
that takes aListableBeanFactory
to find all repository beans defined in it and exposes an API to obtain these instances by domain class (through….getRepository(Class<?> type)
).This class should be used with care. As there's some serious proxy generation going on for the repository instances you have to make sure the
Repositories
instance is created as late as possible during theApplicationContext
creation. The preferred way is to implementApplicationListener
and create the instance by listening to theContextRefreshedEvent
.In case you're writing a web application, the safest way to use
Repositories
is by bootstrapping the repositories in theApplicationContext
created by theContextLoaderListener
and place theRepositories
(see the reference documentation of Spring MVC for details.