如何从自定义实现中引用“常规" spring数据仓库? [英] How to reference the 'normal' spring data repo from a custom implementation?
问题描述
我想通过自定义实现扩展 JpaRepository
,所以我添加了 MyRepositoryCustom
接口和 MyRepositoryImpl
类,以扩展此接口./p>
是否可以通过自定义类中的 JpaRepository
调用方法?
注意:有人还问了这是对 https://stackoverflow.com/a/11881203/40064 的评论,但我认为这很普遍,应该另外提出一个问题.
tl; dr
要将核心存储库接口注入定制实现中,请将 Provider< RepositoryInterface>
注入定制实现中.
详细信息
要正常工作的核心挑战是正确设置依赖项注入,因为您将要在要扩展的对象和扩展之间创建循环依赖关系.但是,可以通过以下方式解决此问题:
接口MyRepository扩展了Repository< DomainType,Long> ;、 MyRepositoryCustom {//查询方法在这里}MyRepositoryCustom接口{//自定义实现方法声明在这里}类MyRepositoryImpl实现MyRepositoryCustom {私有最终提供者< MyRepository>资料库;@Autowired公共MyRepositoryImpl(Provider< MyRepository>存储库){this.repository =储存库;}//在此处实现自定义方法}
这里最重要的部分是使用 Provider< MyRepository>
,这将导致Spring为依赖项创建一个延迟初始化的代理,即使它正在为 MyRepository
放在首位.在自定义方法的实现内部,您可以使用….get()
-方法访问实际的bean.
Provider
是 @Inject
JSR的接口,因此是标准接口,并且需要对该API JAR的附加依赖.如果只想使用Spring,则可以使用 ObjectFactory
作为替代接口,但是会得到完全相同的行为.
I want to extend a JpaRepository
with a custom implementation, so i add a MyRepositoryCustom
interface and a MyRepositoryImpl
class extending this interface.
Is there a way to call methods from JpaRepository
inside my custom class?
Note: This was also asked as a comment on https://stackoverflow.com/a/11881203/40064, but I think it is common enough to deserve a separate question.
tl;dr
To inject the core repository interface into a custom implementation, inject a Provider<RepositoryInterface>
into the custom implementation.
Details
The core challenge to get that working is setting up the dependency injection correctly as you are about to create a cyclic dependency between the object you're about to extend and the extension. However this can be solved as follows:
interface MyRepository extends Repository<DomainType, Long>, MyRepositoryCustom {
// Query methods go here
}
interface MyRepositoryCustom {
// Custom implementation method declarations go here
}
class MyRepositoryImpl implements MyRepositoryCustom {
private final Provider<MyRepository> repository;
@Autowired
public MyRepositoryImpl(Provider<MyRepository> repository) {
this.repository = repository;
}
// Implement custom methods here
}
The most important part here is using Provider<MyRepository>
which will cause Spring to create a lazily-initialized proxy for that dependency even while it's creating an instance for MyRepository
in the first place. Inside the implementation of your custom methods you can then access the actual bean using the ….get()
-method.
Provider
is an interface from the @Inject
JSR and thus a standardized interface and requires an additional dependency to that API JAR. If you want to stick to Spring only, you can used ObjectFactory
as an alternative interface but get the very same behavior.
这篇关于如何从自定义实现中引用“常规" spring数据仓库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!