问题描述
我有一个 spring-boot 应用程序,它现在需要支持多个对象存储并根据环境有选择地使用所需的存储。基本上我所做的是创建一个接口,然后每个存储库实现。
我已经简化了示例的代码。 我根据确定 env 的 spring 配置文件为每种商店类型创建了 2 个 bean:
@Profile("env1")
@Bean
public store1Sdk buildClientStore1() {
return new store1sdk();
}
@Profile("env2")
@Bean
public store2Sdk buildClientStore2() {
return new store2sdk();
}
在服务层中,我已经自动连接了接口,然后在存储库中,我使用了@Profile 来指定要使用的接口实例。
public interface ObjectStore {
String download(String fileObjectKey);
...
}
@Service
public class ObjectHandlerService {
@Autowired
private ObjectStore objectStore;
public String getobject(String fileObjectKey) {
return objectStore.download(fileObjectKey);
}
...
}
@Repository
@Profile("env1")
public class Store1Repository implements ObjectStore {
@Autowired
private Store1Sdk store1client;
public String download(String fileObjectKey) {
return store1client.getobject(storeName,fileObjectKey);
}
}
当我使用配置的“env”启动应用程序时,它实际上按预期运行。但是,在运行测试时,我得到“没有符合 ObjectStore 类型的 bean。预计至少有 1 个 bean 符合自动装配的候选条件。”
@ExtendWith({ SpringExtension.class })
@SpringBoottest(classes = Application.class)
@ActiveProfiles("env1,test")
public class ComposerServiceTest {
@Autowired
private ObjectHandlerService service;
@Test
void download_success() {
String response = service.getobject("testKey");
...
}
}
如测试类的@ActiveProfile 所述,还有一些其他环境,例如开发、测试、生产。我尝试过使用组件扫描,在同一个包中包含 impl 和 interface 等,但没有成功。我觉得我在测试设置中遗漏了一些明显的东西。但是可能与我的整体应用程序配置有关?我的解决方案的主要目标是避免出现很长的
if (store1Sdk != null) {
store1Sdk.download(fileObjectKey);
}
if (store2Sdk != null) {
store2Sdk.download(fileObjectKey);
}
解决方法
试试@ActiveProfiles({"env1","test"})
。
使用 @ActiveProfiles
激活多个配置文件并将配置文件指定为数组。
这个问题是因为Store1Repository使用@Profile("env1")
,当你使用@test
时,这个类不会被调用。尝试删除 @Profile("env1")
的 Store1Repository
。
如果您使用 @test
,两个 store1Sdk/store2Sdk
都不是实例,请尝试添加默认 instanse.eg
:
@Bean
public store2Sdk buildClientStoreDefault() {
return new store2sdk();
}