[英]Why Spring @Qualifier does not work with Spock and Spring Boot
我正在嘗試為Spock編寫控制器測試。
@ContextConfiguration(loader = SpringApplicationContextLoader.class,
classes = [Application.class, CreateUserControllerTest.class])
@WebAppConfiguration
@Configuration
class CreateUserControllerTest extends Specification {
@Autowired
@Qualifier("ble")
PasswordEncryptor passwordEncryptor
@Autowired
UserRepository userRepository
@Autowired
WebApplicationContext context
@Autowired
CreateUserController testedInstance
def "Injection works"() {
expect:
testedInstance instanceof CreateUserController
userRepository != null
}
@Bean
public UserRepository userRepository() {
return Mock(UserRepository.class)
}
@Bean(name = "ble")
PasswordEncryptor passwordEncryptor() {
return Mock(PasswordEncryptor)
}
}
Application類只是Spring Boot最簡單的配置(啟用自動掃描),它提供了一個PasswordEncryptor。 我想用提供模擬的bean替換Application中的bean。
但是不幸的是,Spring拋出了NoUniqueBeanDefinitionException:
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.jasypt.util.password.PasswordEncryptor] is defined: expected single matching bean but found 2: provide,ble
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 54 more
@Qualifier注釋似乎根本不起作用。 我能做什么?
編輯
問題不在CreateUserControllerTest
而在CreateUserController
。
public class CreateUserController {
@Autowired
private PasswordEncryptor encryptor;
}
沒有@Qualifier
批注,因此Spring不知道應該注入哪個bean。 不幸的是,我不知道如何使Spring通過本地配置替換Application中的PasswordEncryptor
bean。
如果您具有相同接口的多個實現,則@Qualifier
將連接bean的特定實例。
但是在春季上下文中,每個bean仍然需要一個“唯一”名稱。
因此,您正在嘗試注冊兩個名為“ passwordEncryptor
”的bean。 一個在您的測試中,另一個似乎在您的實際代碼“ Application.class
”中。
如果要模擬“ PasswordEncryptor”,請使用@Mock
或@Spy
。 (或)如果要避免錯誤,請更改方法的名稱,以避免實例名稱沖突。
@Mock
private PasswordEncryptor passwordEncryptor;
or
@Spy
private PasswordEncryptor passwordEncryptor;
編輯
該錯誤的另一種可能是在代碼中的某個地方,您為“ passwordEncryptor
”定義了@Autowired
,而沒有@Qualifier
標記,
但
您定義了@Bean(name="...") passwordEncryptor
兩個實例,因此Spring上下文很混亂,無法選擇要對字段“自動關聯”的一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.