自动装配 Spring JPA 存储库的 @Primary 等效项

2024-01-13

我在应用程序中使用 Spring JPA 存储库和实体。现在,在该应用程序的某种风格中,我需要扩展我的一个实体并提供一个扩展存储库。

对于我需要覆盖/扩展的所有其他 bean,我只需创建一个新的实现并使用 @Primary 对其进行注释,以便它将自动装配而不是默认实现。

然而,对于存储库来说,这不起作用。我可以使用 @Primary 注释新存储库,但它没有任何效果(两个 bean 都已找到,因此无法自动装配)。这是有道理的,因为存储库是一个接口而不是实现,该实现是由 Spring 动态提供的。

我可以以某种方式告诉Spring(通过存储库上的注释或通过配置)使用哪个存储库吗?或者我必须做这样的手动解决方法在 Spring Data JPA 存储库中使用 @Primary https://stackoverflow.com/questions/30029878/using-primary-in-spring-data-jpa-repositories或者我应该想出一种存储库提供程序而不是自动装配?

Edit为了让事情更清楚: 假设我有一个实体A

@Entity
public class A {
  @Id
  private long id;
}

及其存储库

public ARepository extends Repository<A, Long> {
}

现在我将其扩展到实体B

@Entity
public class B extends A {
}

public interface BRepository extends ARepository {
}

通常,根据文档,您使用这样的存储库:

@Autowired
private ARepository repository;

然而,这不起作用,因为现在有两个类型的 beanARepository。对于我自己实现的bean,我会使用@Primary在扩展类上,但对于存储库,在编译时没有接口的实现。


我会改编这个答案的想法:https://stackoverflow.com/a/27549198/280244 https://stackoverflow.com/a/27549198/280244和这个 git 示例https://github.com/netgloo/spring-boot-samples/tree/master/spring-boot-springdatajpa-inheritance/src/main/java/netgloo/models https://github.com/netgloo/spring-boot-samples/tree/master/spring-boot-springdatajpa-inheritance/src/main/java/netgloo/models

引入一个通用的抽象Repository,标记为@NoRepositoryBean

@NoRepositoryBean
public interface AbstractARepository<T extends A>
                                    extends Repository<T, Long> {
    T findByName(String name); //or what ever your queries are
}

public ARepository extends AbstractARepository<A> {
   //almost emtpy
}


public BRepository extends AbstractARepository<B> {
   //queries that are special for B
}

现在您可以注入ARepository and BRepository,并且两者都是类型保存!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自动装配 Spring JPA 存储库的 @Primary 等效项 的相关文章

随机推荐