我有一颗豆子:
@Bean("imageKitPath")
public String imageKitPath() {
return "/main";
}
然而,在测试中,我希望这个Bean具有/test
值.我成功地实现了这一点:
@Bean
@Primary
public String imageKitPath2() {
return "/test";
}
现在,问题来了.我还成功地实现了基于JWT的身份验证.然而,我希望有不同的签名测试和生产.
在我的生产代码中,我有一个带有JWT签名的Bean:
@Bean("jwtKey")
public String jwtKey() {
// some logic to read key from file
return jwtKey;
}
并且,与前面的示例类似,在测试中它看起来如下所示:
@Bean
@Primary
public String jwtKey2() {
// some logic to read key from application.properties
return jwtKey;
}
这两个Bean都是正确创建的,并且都有我期望它们具有的值.问题在于将这些值注入其他组件.例如,在我的JwtService
个班级(这是@Service
个注释的班级)中,我很难将它们自动化.我已经try 了多种解决方案.
1.
private final String jwtKey;
@Autowired
public JwtService(String jwtKey) {
this.jwtKey = jwtKey;
}
在没有第二个Bean(jwtKey2
)的生产中,这将工作得很好.但是,测试将无法加载具有org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: more than one 'primary' bean found among candidates
的上下文.
2.
private final String jwtKey;
@Autowired
public JwtService(@Qualifier("jwtKey") String jwtKey) {
this.jwtKey = jwtKey;
}
同样,在生产中可以工作,但在测试中它将使用产品的JWT值,而不是我在测试中指定的值.
3.
private final String jwtKey;
@Autowired
public JwtService(@Qualifier("jwtKey2") String jwtKey) {
this.jwtKey = jwtKey;
}
这个在测试中可以正常工作,但是--显然--在生产中会失败,因为没有jwtKey2
Bean.
我描述imageKitPath
Bean的原因很简单.因为测试指定了一个使用@Primary
覆盖imageKitPath
的Bean,所以我认为Spring无法区分imageKitPath2
和jwtKey2
.删除imageKitPath
个Bean完全解决了JWT的Bean问题.