如何检索给定域类的spring数据存储库实例? [英] How to retrieve spring data repository instance for given domain class?
问题描述
给定某些类中所有spring数据存储库的列表 Bar
:
Given the list of all spring data repositories in some class Bar
:
@Autowired
private List<Repository> repositories;
如何找到现有域类的存储库 Foo
在上面的列表中?
How can I find the repository for an existing domain class Foo
in the above list?
假设存在以下内容:
@Entity
public class Foo {
...
}
和
public interface FooRepository extends JpaRepository<Foo, String> {}
推荐答案
Spring Data Commons包含一个类存储库
使用 ListableBeanFactory
查找其中定义的所有存储库bean并公开API以通过域类获取这些实例(通过 ... .getRepository(Class<?> type)
)。
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)
).
应谨慎使用此类。由于存储库实例正在进行一些严格的代理生成,因此必须确保在 ApplicationContext期间尽可能晚地创建
创建。首选方法是实现存储库
实例 ApplicationListener
并通过监听 ContextRefreshedEvent
来创建实例。
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
.
如果您正在编写Web应用程序,使用存储库
的最安全方法是引导中的存储库ApplicationContext
由 ContextLoaderListener
创建并放置存储库
(参见参考文档。
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.
这篇关于如何检索给定域类的spring数据存储库实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!