我的项目有以下两个存储库和一个服务类:
@Repository
public interface FooRepository extends JpaRepository<Foo, Long> {...}
@Repository
public interface FooExtRepository extends FooRepository {...}
@Service
public class FooService {
private final FooRepository fooRepository;
public FooService(FooRepository fooRepository, ...){...}
...
}
编译项目后,出现以下错误。
Parameter 2 of constructor in FooService required a single bean, but 2 were found:
- fooExtRepository: defined in FooRepositoryExt defined in @EnableJpaRepositories declared on DatabaseConfiguration
- fooRepository: defined in FooRepository defined in @EnableJpaRepositories declared on DatabaseConfiguration
This may be due to missing parameter name information
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
FooService 仅请求 FooRepository bean,而不请求 FooExtRepository。为什么Spring在FooService类中找到FooRepository bean注入的两个Bean?从面向对象编程的角度来看,FooRepository 的实例和 FooExtRepository 的实例不是同一个对象。
为了解决此编译错误,我将 FooRepository 替换为 FooExtRepository。
您的两个 bean 都实现了
FooRepository
,这就是为什么它们是自动装配的候选者。这实际上与 Spring Data 无关,而是 Spring 依赖注入容器从根本上是如何工作的。
如果您始终希望在此类场景中注入
FooRepository
,请按照错误消息中给出的建议进行操作,并用 @Primary
进行注释。这仍然允许 FooExtRepository
在明确引用该注入点的地方进行连接,只有一个候选点可以开始。