springboot-条件化注解

  在项目中,有时会遇到我们的Configuration、Bean、Service等等的bean组件需要依条件按需加载的情况。那么Spring Boot怎么做的呢?它为此定义了许多有趣的条件,当我们将它们运用到我们的bean上时,就可以实现动态的加载控制了。

  自动配置中使用的条件化注解

  举个栗子:公司同事做了一个公用的sso服务,业务系统可以选择性进行集成。当配置文件设置sso.enabled = true时,启动单点登录。当设置sso.enabled = false时,使用spring-security。

  • 配置文件

       

  • spring-security配置类的条件化加载
/**
 * Security登录认证配置
 * @author hua.huang
 */
//@EnableWebSecurity  // 启动SpringSecurity
@ConditionalOnProperty(value = "sso.enable",matchIfMissing = true,havingValue = "false")
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
ConditionalOnProperty的属性说明
https://blog.csdn.net/shixin_li/article/details/80532866
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {
    //数组,获取对应property名称的值,与name不可同时使用。 作用:value单独使用时:当对应property名称的值为false时,该configuration不生效;当对应property名称的值为除false之外的值时,该configuration生效
    String[] value() default {};
 
    //字符串,property名称的前缀,可有可无,可以与name组合使用
    String prefix() default "";
 
    //数组,property完整名称或部分名称(可与prefix组合使用,组成完整的property名称),与value不可同时使用。 作用与value一样
    String[] name() default {};
 
    //可与name、value(name和value不能同时存在)组合使用,比较获取到对应property名称的值与havingValue给定的值是否相同:如果相同,该configuration生效,反之,不生效 
    String havingValue() default "";
 
        //缺少该property时是否可以加载。如果为true,没有该property也会正常加载;反之报错
    boolean matchIfMissing() default false;
 
    //不需要管它
    boolean relaxedNames() default true;
 
}
原文地址:https://www.cnblogs.com/MrSi/p/9529918.html