国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

淺談關于spring profile的誤解

2024-07-14 08:42:02
字體:
來源:轉載
供稿:網友

背景

spring的profile大家都是用的溜的飛起~

那么profile的組合如何使用呢???

比如我們這樣使用

@Profile({"prod", "unit-test"})

分析

上述的profile大家應該不會存有疑問 當profile為prod或者unit-test的時候才會生效。

但是如果我們使用非呢~如何確保在某些情況下不生效!

spring提供了常見的!來進行描述

因此如果想要在非生產環境生效只要簡單的寫成

@Profile({"!prod"})

那么如何在多個環境下不生效呢???

自作聰明的某些人【我】如下代碼

@Profile({"!prod", "!unit-test"})

那么實際情況是否如此呢???

我們看一下對應的代碼

代碼

profile是通過profileCondition來完成控制的

class ProfileCondition implements Condition {   @Override  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {   if (context.getEnvironment() != null) {     MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());     if (attrs != null) {      for (Object value : attrs.get("value")) {        if (context.getEnvironment().acceptsProfiles(((String[]) value))) {         return true;        }      }      return false;     }   }   return true;  } }

很明顯可以看到了acceptsProfiles

/** * Return whether one or more of the given profiles is active or, in the case of no * explicit active profiles, whether one or more of the given profiles is included in * the set of default profiles. If a profile begins with '!' the logic is inverted, * i.e. the method will return true if the given profile is <em>not</em> active. * For example, <pre class="code">env.acceptsProfiles("p1", "!p2")</pre> will * return {@code true} if profile 'p1' is active or 'p2' is not active. * @throws IllegalArgumentException if called with zero arguments * or if any profile is {@code null}, empty or whitespace-only * @see #getActiveProfiles * @see #getDefaultProfiles */boolean acceptsProfiles(String... profiles);

從上述可以看到應該是or的條件

當然代碼如下

@Overridepublic boolean acceptsProfiles(String... profiles) {  Assert.notEmpty(profiles, "Must specify at least one profile");  for (String profile : profiles) {   if (StringUtils.hasLength(profile) && profile.charAt(0) == '!') {     if (!isProfileActive(profile.substring(1))) {      return true;     }   }   else if (isProfileActive(profile)) {     return true;   }  }  return false;}

因此可以看到當是!條件的時候會判斷如果當前未激活profile返回true 否則當前是正常條件的換當前profile如果激活則返回true 當上述條件都不滿足才返回false

因此上述邏輯告訴我們其實應該是或者的邏輯。因此

@Profile({"!prod", "!unit-test"})

!prod||!unit-test===>!(prod&&unit-test)  也就是說當prod和unit-test都生效的時候才不會注冊 其他調均都會注冊生效

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 游戏| 车致| 平凉市| 兴和县| 深泽县| 太谷县| 灵宝市| 东辽县| 天等县| 锡林郭勒盟| 宁陕县| 丰原市| 青州市| 铜山县| 台前县| 桓台县| 饶河县| 通榆县| 大港区| 沙湾县| 邓州市| 台山市| 山阴县| 宜都市| 博野县| 闸北区| 益阳市| 延长县| 城步| 精河县| 曲周县| 雷波县| 洪湖市| 高尔夫| 江门市| 油尖旺区| 定远县| 佛冈县| 文山县| 莫力| 宝坻区|