亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

spring如何根據profile調用bean的不同實現

spring如何根據profile調用bean的不同實現

拉丁的傳說 2022-10-26 15:53:55
我需要添加一個接口的多個實現,并且應該根據配置文件選擇其中一個。例如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 運算符 (!) 為前綴,則在配置文件未激活時將注冊帶注釋的組件


查看完整回答
反對 回復 2022-10-26
?
富國滬深

TA貢獻1790條經驗 獲得超9個贊


您可以添加@ConditionalOnMissingBean到 Service2 這意味著它將僅在不存在其他實現的情況下使用,這將有效地使 Service2 成為除本地以外的任何其他配置文件中的默認實現


@Service

@ConditionalOnMissingBean

class Service2 implements Test {

    public void test() {}

}


查看完整回答
反對 回復 2022-10-26
  • 2 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號