【问题标题】:NoUniqueBeanDefinitionException when injecting JpaRepository to Generic class将 JpaRepository 注入通用类时出现 NoUniqueBeanDefinitionException
【发布时间】:2016-04-20 15:46:49
【问题描述】:

如何将存储库注入泛型类?

public class FruitComboBox<T extends Fruit> extends ComboBox {

    @Autowired
    private JpaRepository<T, Integer> repository;
    ...
}

public class FruitMarket {

    @Autowired
    FruitComboBox<Apple> appleCombobox; // Apple extends Fruit

    @Autowired
    FruitComboBox<Orange> orangeCombobox; // Orange extends Fruit

    ...
}

我还有两个仓库

@Repository
public interface AppleRepository extends JpaRepository<Apple, Integer> {
}

@Repository
public interface OrangeRepository extends JpaRepository<Orange, Integer> {
}

我认为来自 FruitComboBox 的通用存储库应该根据它的 T 解析为两个现有存储库之一,并由 Spring 自动装配。

NoUniqueBeanDefinitionException: expected single matching bean but found 2 发生在运行时(不是在应用程序启动时)。所以我认为在运行时定义了所有类型,并且 Spring 已经知道具体类型是 T。

【问题讨论】:

  • 这方面有什么进展吗?我有一个类似的问题,对我来说,这听起来像一个错误!

标签: java generics spring-boot autowired


【解决方案1】:

Spring 数据需要在引导时知道存储库所代表的实体。这意味着您不能在自动装配期间将其留在Generic Parameter

创建一个单独的界面,如下所示。

@Repository
public interface MyGenericRepository<T> extends JpaRepository<T, Integer>{

}

现在您应该能够使用确定的类型(不是泛型类型)自动装配它。这是通用的。

@Autowired
private MyGenericRepository<Apple, Integer> repository;

上面不能留下泛型参数。

参考http://docs.spring.io/spring-data/jpa/docs/1.6.5.RELEASE/reference/html/repositories.html

同时尝试使用Long 作为 ID。

【讨论】:

  • 谢谢,但我调查了自动装配实际存在的存储库的可能性。我给出了更准确的定义,请看问题
猜你喜欢
  • 1970-01-01
  • 2013-03-30
  • 2017-08-31
  • 1970-01-01
  • 2022-01-04
  • 2015-12-29
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
相关资源
最近更新 更多