如何从自定义实现中引用“正常"弹簧数据存储库? [英] How to reference the 'normal' spring data repo from a custom implementation?

查看:14
本文介绍了如何从自定义实现中引用“正常"弹簧数据存储库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用自定义实现扩展 JpaRepository,因此我添加了一个 MyRepositoryCustom 接口和一个扩展此接口的 MyRepositoryImpl 类.

I want to extend a JpaRepository with a custom implementation, so i add a MyRepositoryCustom interface and a MyRepositoryImpl class extending this interface.

有没有办法在我的自定义类中从 JpaRepository 调用方法?

Is there a way to call methods from JpaRepository inside my custom class?

注意:这也是对 https://stackoverflow.com/a/11881203/40064 的评论而提出的,但我认为这很常见,值得单独提出一个问题.

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

要将核心存储库接口注入自定义实现,请将 Provider 注入自定义实现.

实现这一目标的核心挑战是正确设置依赖注入,因为您将要在要扩展的对象和扩展之间创建循环依赖.然而,这可以解决如下:

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
}

这里最重要的部分是使用 Provider 这将导致 Spring 为该依赖项创建一个延迟初始化的代理即使它正在为 MyRepository<创建一个实例/code> 放在首位.在自定义方法的实现中,您可以使用 ....get() 方法访问实际的 bean.

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 是来自 @Inject JSR 的接口,因此是标准化的接口,需要对该 API JAR 的附加依赖项.如果您只想坚持使用 Spring,您可以使用 ObjectFactory 作为替代接口,但获得完全相同的行为.

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.

这篇关于如何从自定义实现中引用“正常"弹簧数据存储库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆