Spring 选择甚至不实现存储库接口的存储库实现



我在不同的包中有两个接口:

package com.domain1
@Repository //expect that Spring will generate a bean
public interface PersonRepository extends org.springframework.data.repository.Repository<Person, UUID> {}

package com.domain2
//just an interface
public interface PersonRepository extends org.springframework.data.repository.Repository<Person, UUID> {}
//implementation
@Component
public PersonRepositoryImpl implements com.domain2.PersonRepository {}

我尝试注入第一个存储库:

public class MyClass {
@Autowired
com.domain1.PersonRepository personRepository;
}

我希望spring数据jpa从domain1包注入一个存储库,但不是注入com.domain2.PersonRepositoryImpl(一个不实现com.domain1.PersonRepository接口的组件(。

我试过使用限定符,但没有帮助。

这是一个bug或功能吗?:(

附言:当然,如果我更改接口名称,那么一切都会按预期进行。

这当然是一个特性。接口不能实例化,相反,它们的实现是。Spring将查找特定接口的所有实现,如果它能够识别一个唯一的接口(在您的情况下(,它将使用该实现。

如果你有不止一个,它会给你一个例外,说autowire有多个候选人,它不能独立选择一个。在这种情况下,您必须使用@Qualifer来指定您想要的实现。

最新更新