@ConditionalOnProperty註解是用來作爲條件,配置它所配置的類等是否生效。
1,@ConditionalOnProperty源代碼
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional({OnPropertyCondition.class})
public @interface ConditionalOnProperty {
String[] value() default {};//與name相同作用
String prefix() default "";//配置文件中的前綴
String[] name() default {};//配置文件中的名稱
String havingValue() default "";//name對應的值
boolean matchIfMissing() default false;//缺少配置時是否生效
}
2,使用方式
隨便一個例子說明:
(1)配置文件
這是分佈式鎖啓用配置類開關,爲true表示啓用分佈式鎖
redission.enable=true
(2)
注入分佈式鎖RLock的Bean,打上註解。
prefix:配置前綴redission
name:後綴enable
havingValue:該值與redission.enable配置的值相同,則注入RLock的Bean生效
matchIfMissing:true標識如果沒有配置redission.enable=true,默認是生效的,false默認沒有配置不生效
@Configuration
public class CommonConfig {
@Bean
@ConditionalOnProperty(prefix = "redission", name = "enable", havingValue = "true", matchIfMissing = true)
public RLock rLock() {
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
return redisson.getLock("lock");
}
}
此時如果配置文件中redission.enable=false,則失敗。