我需要添加一個接口的多個實現,并且應該根據配置文件選擇其中一個。例如interface Test{ public void test();}@Service@Profile("local")class Service1 implements Test{ public void test(){ }}@Serviceclass Service2 implements Test{ public void test(){ }}@SpringBootApplicationpublic class Application { private final Test test; public Application(final Test test) { this.test = test; } @PostConstruct public void setup() { test.test(); }}我的意圖是當我使用 -Dspring.profiles.active=local 時,應該調用 Service1,否則應該調用 service2,但我得到一個異常,即缺少 Test 的 bean。
2 回答

阿晨1998
TA貢獻2037條經驗 獲得超6個贊
添加默認配置文件Service2:
@Service
@Profile("default")
class Service2 implements Test{
public void test(){
}
}
只有在沒有識別出其他配置文件時,才會將 bean 添加到上下文中。如果您傳入不同的配置文件,例如 -Dspring.profiles.active="demo",則忽略此配置文件。
如果您想要除本地使用NOT 運算符之外的所有配置文件:
@Profile("!local")
如果給定配置文件以 NOT 運算符 (!) 為前綴,則在配置文件未激活時將注冊帶注釋的組件

富國滬深
TA貢獻1790條經驗 獲得超9個贊
您可以添加@ConditionalOnMissingBean到 Service2 這意味著它將僅在不存在其他實現的情況下使用,這將有效地使 Service2 成為除本地以外的任何其他配置文件中的默認實現
@Service
@ConditionalOnMissingBean
class Service2 implements Test {
public void test() {}
}
添加回答
舉報
0/150
提交
取消