返回介绍

4.6.2 为所有的repositories添加自定义方法

发布于 2020-08-26 12:31:29 字数 3953 浏览 1128 评论 0 收藏 0

如果想要给为所有的repository接口增加一个方法,那么之前的方法是不可行的。为了给所有的repository添加自定义的方法,开发者首先需要定义一个中间过渡的接口。

Example 20. An interface declaring custom shared behavior(定义中间接口声明)

@NoRepositoryBean
public interface MyRepository<T, ID extends Serializable>
  extends PagingAndSortingRepository<T, ID> {

  void sharedCustomMethod(ID id);
}

现在,开发者的其他repository接口需要继承定义的中间接口而不是继承Repository接口。接下来需要为这个中间接口创建实现类。这个实现类是基于Repository中的基类的(不同的持久化存储继承的基类也不相同,这里以Jpa为例),这个类会被当做repository代理的自定义类来执行。 Example 21. Custom repository base class(自定义reposotory基类)

public class MyRepositoryImpl<T, ID extends Serializable>
  extends SimpleJpaRepository<T, ID> implements MyRepository<T, ID> {

  private final EntityManager entityManager;

  public MyRepositoryImpl(JpaEntityInformation entityInformation,EntityManager entityManager) {
    super(entityInformation, entityManager);

    // Keep the EntityManager around to used from the newly introduced methods.
    this.entityManager = entityManager;
  }

  public void sharedCustomMethod(ID id) {
    // implementation goes here
  }
}

Spring中命名空间默认会为base-package下所有的接口提供一个实例。但MyRepository只是作为一个中间接口,并不需要创建实例。所以我们可以使用@NoRepositoryBean注解或将其排除在base-package的配置中

最后一步是使用JavaConfig或Xml配置这个自定义的repository基类。

Example 22. Configuring a custom repository base class using JavaConfig(使用JavaConfig配置repository基类)

@Configuration
@EnableJpaRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }

也可使用Xml的方式配置。

Example 23. Configuring a custom repository base class using XML(使用xml配置自定义repository基类)

<repositories base-package="com.acme.repository"
     repository-base-class="….MyRepositoryImpl" />

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文