@ConditionalOnProperty控制Configuration是否生效

1. 背景

Spring Boot通过@ConditionalOnProperty来控制Configuration是否生效。

最近项目有2个微服务实例A和B,在common服务上添加了TenancyInterceptor使用了@ConditionalOnProperty注解,然后在A服务properties中设置了config.tenancy.enable=true,在B服务properties中设置了config.tenancy.enable=false

这样A服务里面的sql操作就都会触发TenancyInterceptor类的方法逻辑(该类方法我用作mybatisPlus的sql拦截注入rentId),B服务的因为配置为false,所以就不会自动追加

2. 说明

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {

    String[] value() default {}; //数组,获取对应property名称的值,与name不可同时使用  
  
    String prefix() default "";//property名称的前缀,可有可无  
  
    String[] name() default {};//数组,property完整名称或部分名称(可与prefix组合使用,组成完整的property名称),与value不可同时使用  
  
    String havingValue() default "";//可与name组合使用,比较获取到的属性值与havingValue给定的值是否相同,相同才加载配置  
  
    boolean matchIfMissing() default false;//缺少该property时是否可以加载。如果为true,没有该property也会正常加载;反之报错  
  
    boolean relaxedNames() default true;//是否可以松散匹配,至今不知道怎么使用的  
} 
}

3. 使用方法

通过其两个属性name以及havingValue来实现的,其中name用来从application.properties中读取某个属性值。
如果该值为空,则返回false;
如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。


如果返回值为false,则该configuration不生效;为true则生效。

4. common使用注解的代码

//在application.properties配置"config.tenancy.enable",对应的值为true
//config.tenancy.enable=true

/**
 * <p>
 * 多租户、sql日志
 * </p>
 */
@Component
@EnableConfigurationProperties(TenancyProperties.class)
@ConditionalOnProperty(prefix = "config.tenancy", name = "enable", havingValue = "true")
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class }) })
public class TenancyInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Exception {
        //mybatisPlus的sql拦截注入,这里做多租户的sql追加rent_id
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Venlenter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值