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

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-data-jpa从domain1包中注入一个存储库,但不是它,而是注入com.domain2.PersonRepositoryImpl(一个不实现com.domain1.PersonRepository接口的组件)。

我尝试使用限定词-没有帮助。

这是错误还是功能? :)

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

最佳答案

这是当然的功能。接口不能实例化,相反,它们的实现是实例化的。 Spring会查找特定接口的所有实现,如果它可以标识一个唯一的接口(您的情况),它将使用该实现。

如果您有不止一个,它将给您一个例外,说明该自动接线有多个候选对象,并且不能独立选择一个。在这种情况下,您必须使用@Qualifer指定所需的实现。

10-06 05:41