How to retrieve spring data repository instance for given domain class?(如何检索给定域类的弹簧数据存储库实例?)
问题描述
给定某个类 Bar
中所有 Spring 数据存储库的列表:
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 包含一个类 Repositories
,它采用 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
创建期间尽可能晚地创建 Repositories
实例.首选方式是实现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 应用程序,使用 Repositories
最安全的方法是在 ContextLoaderListener 创建的
code> 并放置 ApplicationContext
中引导存储库Repositories
(参见 参考文档 Spring MVC 了解详情.
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.
这篇关于如何检索给定域类的弹簧数据存储库实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检索给定域类的弹簧数据存储库实例?


- Eclipse 插件更新错误日志在哪里? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01