You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为JpaRepository使用泛型?注入时遇多Bean冲突问题

问题:JpaRepository泛型解耦导致Bean注入冲突

我尝试通过泛型封装JpaRepository,实现核心代码与Spring Data JPA、Spring Boot解耦,用自定义处理器访问数据,但出现了Bean注入冲突错误:

字段com.ecobike.database.handler.CRUD中的repository需要单个Bean,但找到3个:

  • customerRepository:定义于@EnableJpaRepositories标注的JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration中的com.ecobike.database.repository.CustomerRepository
  • dockRepository:定义于@EnableJpaRepositories标注的JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration中的com.ecobike.database.repository.DockRepository
  • repositoryProxy:定义于@EnableJpaRepositories标注的JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration中的com.ecobike.database.repository.RepositoryProxy

解决方案建议

  • 将其中一个Bean标记为@Primary,让Spring优先选择该Bean进行注入
  • 更新消费端逻辑,使其支持接收多个Bean实例
  • 使用@Qualifier注解指定要注入的具体Bean

代码示例

CustomerRepository.java

public interface CustomerRepository extends RepositoryProxy<Customer> {
}

DockRepository.java

public interface DockRepository extends RepositoryProxy<Dock> {
}

RepositoryProxy.java

public interface RepositoryProxy<T> extends JpaRepository<T, Long> {
}

CRUD.java

@Component
public class CRUD<T> {
    @Autowired
    private JpaRepository<T, Long> repository;

    public void create(T object) {
    }

    public List<T> getAll() {
        return repository.findAll();
    }

    public T get(String id) {
        return null;
    }

    public void update(T object) {
    }

    public void delete(T object) {
    }
}

CustomerDBHandler.java

public class CustomerDBHandler extends CRUD<Customer> {
    @Getter
    private static final CustomerDBHandler instance = new CustomerDBHandler();
}

DockDBHandler.java

public class DockDBHandler extends CRUD<Dock> {
    @Getter
    private static final DockDBHandler instance = new DockDBHandler();
}

内容的提问来源于stack exchange,提问作者vcth4nh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:12:49