@ConditionalOnProperty注解控制组件是否注入spring的注解
@Configuration
@Slf4j
@EnableScheduling
//@Conditional(CheckEnvironmentCondition.class)
@ConditionalOnProperty(prefix = "demo", name = "conditional", havingValue = "true", matchIfMissing = true)
public class ConditionalConfigTest {
@Scheduled(cron = "*/5 * * * * ?")
private void updateJob(){
System.out.println("ConditionalOnProperty---Test:"+ LocalDateTime.now());
}
}
配置参数匹配,成功注入
各属性作用 源码
@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;
}
havingValue:定义的值是否相等,决定是否注入。
matchIfMissing:如果没有设置这个属性,是否需要havingValue去匹配。
百度后,对于这两个组合使用时,解释的很绕,简单说来:
matchIfMissing为true 比较对象为null时,会注入。
一起使用时,以havingValue为准。