Springboot實(shí)現(xiàn)根據(jù)條件切換注入不同實(shí)現(xiàn)類的示例代碼
最近有個(gè)一需求需要根據(jù)外界環(huán)境的屬性(操作系統(tǒng) || yml屬性 || 其他bean的狀態(tài)) 來(lái)實(shí)現(xiàn)啟動(dòng)時(shí)注入兩套不同的實(shí)現(xiàn)類, 實(shí)現(xiàn)切換.
實(shí)現(xiàn)啟動(dòng)時(shí)條件注入分2步:
第一步 使用@Conditional(參數(shù)為 True false條件實(shí)現(xiàn)類 需要你自己實(shí)現(xiàn))注解
@Conditional(RabbitMqCondition.class)public class RabbitmqSMSMsgServiceImpl extends RabbitmqBasicMsgService {// @Autowired(required = false)// DefaultMQProducer producer; @Override public void sendToYourTaskQueue_Step2(PnsMessage pnsMessage) { // TODO rabbitmq 實(shí)現(xiàn)SMS消息推送 }}
第二步 實(shí)現(xiàn)自定義的條件類接口Condition 實(shí)現(xiàn)matches方法:
我這里判斷的是spring配置文件里的屬性, 其實(shí)可以判斷非常廣泛的東西, 并不只限于屬性.
public class RabbitMqCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return 'rabbitmq'.equals(conditionContext.getEnvironment().getProperty('mq.type')); }}
application.yml 可以切換屬性
mq: type: rabbitmq
如果要是有多個(gè)符合條件的bean 利用@Service(value=“區(qū)別開來(lái)”)
到此這篇關(guān)于Springboot實(shí)現(xiàn)根據(jù)條件切換注入不同實(shí)現(xiàn)類的示例代碼的文章就介紹到這了,更多相關(guān)Springboot 根據(jù)條件切換注入不同實(shí)現(xiàn)類內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 使用python tkinter開發(fā)一個(gè)爬取B站直播彈幕工具的實(shí)現(xiàn)代碼2. ThinkPHP6使用JWT+中間件實(shí)現(xiàn)Token驗(yàn)證實(shí)例詳解3. python 實(shí)時(shí)調(diào)取攝像頭的示例代碼4. Python使用oslo.vmware管理ESXI虛擬機(jī)的示例參考5. Python如何解決secure_filename對(duì)中文不支持問(wèn)題6. Python類成員繼承重寫的實(shí)現(xiàn)7. ASP基礎(chǔ)入門第二篇(ASP基礎(chǔ)知識(shí))8. Python 用NumPy創(chuàng)建二維數(shù)組的案例9. python安裝sklearn模塊的方法詳解10. 不使用XMLHttpRequest對(duì)象實(shí)現(xiàn)Ajax效果的方法小結(jié)
