SpringFramework之@Profile注解

    SpringFrame的版本5.0.9.release。java

    咱们会使用@Profile来分开开发环境和生产环境,Profile是如何实现的呢,如List-1,注意@Conditional的value是ProfileConditiongit

    List-1github

@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。spring

    List-2ide

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这个注解了,看个人另外一篇文章spa

Reference

  1. 源码
相关文章
相关标签/搜索