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. asp下利用xml打包網(wǎng)站文件2. XSL簡(jiǎn)明教程3. Jsp servlet驗(yàn)證碼工具類分享4. JavaScript css3實(shí)現(xiàn)簡(jiǎn)單視頻彈幕功能5. IntelliJ IDEA 2020最新激活碼(親測(cè)有效,可激活至 2089 年)6. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效7. idea重置默認(rèn)配置的方法步驟8. Java IO字符流緩沖區(qū)實(shí)現(xiàn)原理解析9. 使用 Python 實(shí)現(xiàn)微信消息的一鍵已讀的思路代碼10. ASP.Net Core對(duì)USB攝像頭進(jìn)行截圖
