package org.springframework.boot.autoconfigure.condition;import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;import org.springframework.context.annotation.Conditional;
import org.springframework.core.env.Environment;@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {/*** Alias for {@link #name()}.* @return the names*/String[] value() default {};/*** A prefix that should be applied to each property. The prefix automatically ends* with a dot if not specified. A valid prefix is defined by one or more words* separated with dots (e.g. {@code "acme.system.feature"}).* @return the prefix*/String prefix() default "";/*** The name of the properties to test. If a prefix has been defined, it is applied to* compute the full key of each property. For instance if the prefix is* {@code app.config} and one value is {@code my-value}, the full key would be* {@code app.config.my-value}* <p>* Use the dashed notation to specify each property, that is all lower case with a "-"* to separate words (e.g. {@code my-long-property}).* @return the names*/String[] name() default {};/*** The string representation of the expected value for the properties. If not* specified, the property must <strong>not</strong> be equal to {@code false}.* @return the expected value*/String havingValue() default "";/*** Specify if the condition should match if the property is not set. Defaults to* {@code false}.* @return if the condition should match if the property is missing*/boolean matchIfMissing() default false;}
- name: 指定要检查的属性名。
- havingValue: 指定属性应该具有的值,以便条件匹配。
- matchIfMissing: 指定如果属性不存在,条件是否应该匹配。默认值是 false,表示如果属性不存在,条件不匹配。
使用示例
假设我们有一个自动配置类,它基于某个属性 myapp.feature.enabled 来决定是否启用某个功能:
@Configuration
@ConditionalOnProperty(name = "myapp.feature.enabled", havingValue = "true", matchIfMissing = true)
public class MyFeatureAutoConfiguration { @Bean public MyFeature myFeature() { return new MyFeature(); }
}
在这个例子中:
name = “myapp.feature.enabled”: 指定要检查的属性名是 myapp.feature.enabled。
havingValue = “true”: 指定只有当属性值为 true 时,条件才匹配。
matchIfMissing = true: 指定如果属性 myapp.feature.enabled 不存在,条件也应该匹配(即自动启用这个功能)。
可能的配置情况
#属性存在且值为 true:
myapp.feature.enabled=true
#条件匹配,MyFeature Bean 会被创建。
#属性存在且值为 false:
myapp.feature.enabled=false
#条件不匹配,MyFeature Bean 不会被创建。
#属性不存在:
# myapp.feature.enabled 不在配置文件中
注解的matchIfMissing = true
#条件匹配,MyFeature Bean 会被创建。