背景
那么profile的組合如何使用呢???
比如我們這樣使用
1
|
@profile ({ "prod" , "unit-test" }) |
分析
上述的profile大家應(yīng)該不會(huì)存有疑問 當(dāng)profile為prod或者unit-test的時(shí)候才會(huì)生效。
但是如果我們使用非呢~如何確保在某些情況下不生效!
spring提供了常見的!來(lái)進(jìn)行描述
因此如果想要在非生產(chǎn)環(huán)境生效只要簡(jiǎn)單的寫成
1
|
@profile ({ "!prod" }) |
那么如何在多個(gè)環(huán)境下不生效呢???
自作聰明的某些人【我】如下代碼
1
|
@profile ({ "!prod" , "!unit-test" }) |
那么實(shí)際情況是否如此呢???
我們看一下對(duì)應(yīng)的代碼
代碼
profile是通過profilecondition來(lái)完成控制的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** * 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); |
從上述可以看到應(yīng)該是or的條件
當(dāng)然代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@override public 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 ; } |
因此可以看到當(dāng)是!條件的時(shí)候會(huì)判斷如果當(dāng)前未激活profile返回true 否則當(dāng)前是正常條件的換當(dāng)前profile如果激活則返回true 當(dāng)上述條件都不滿足才返回false
因此上述邏輯告訴我們其實(shí)應(yīng)該是或者的邏輯。因此
1
|
@profile ({ "!prod" , "!unit-test" }) |
!prod||!unit-test===>!(prod&&unit-test) 也就是說(shuō)當(dāng)prod和unit-test都生效的時(shí)候才不會(huì)注冊(cè) 其他調(diào)均都會(huì)注冊(cè)生效
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://my.oschina.net/qixiaobo025/blog/1927580