Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

java - How to retrieve spring data repository instance for given domain class?

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> {}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Spring Data Commons contains a class Repositories that takes a ListableBeanFactory 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 the ApplicationContext creation. The preferred way is to implement ApplicationListener and create the instance by listening to the ContextRefreshedEvent.

In case you're writing a web application, the safest way to use Repositories is by bootstrapping the repositories in the ApplicationContext created by the ContextLoaderListener and place the Repositories (see the reference documentation of Spring MVC for details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...