SpringFramework之@Profile註解
阿新 • • 發佈:2019-06-23
SpringFrame的版本5.0.9.release。
我們會使用@Profile來分開開發環境和生產環境,Profile是如何實現的呢,如List-1,注意@Conditional的value是ProfileCondition
List-1
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional(ProfileCondition.class) public @interface Profile { /** * The set of profiles for which the annotated component should be registered. */ String[] value(); }
如下List-2,ProfileCondition實現了Condition介面,重點在於matches方法,獲得Profile的value值,之後用Environment的acceptsProfiles方法判斷是否是可以接受的profile。
List-2
package org.springframework.context.annotation; import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.util.MultiValueMap; /** * @author Chris Beams * @author Phillip Webb * @author Juergen Hoeller * @since 4.0 */ class ProfileCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { 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; } }
引出一個問題,這個ProfileCondition是何時被呼叫的呢,這個就要了解@Conditional這個註解了,看我的另一篇文章。