SpringBoot之@ConditionalOnProperty注解使用方法

目录
  • 1、SpringBoot实现
    • 1.1 设置配置属性
    • 1.2 编写加载类
  • 2、ConditionalOnProperty属性与源码
    • 2.1 属性
    • 2.2 源码

@ConditionalOnProperty:根据属性值来控制类或某个方法是否需要加载。它既可以放在类上也可以放在方法上。

1、SpringBoot实现

1.1 设置配置属性

在applicatio.properties或application.yml配置isload_bean = true;

#配置是否加载类
is_load_bean: true

1.2 编写加载类

编写加载类,使用@Component进行注解,为了便于区分,我们将@ConditionalOnProperty放在方法上。

/**
 * @author: jiangjs
 * @description: 使用@ConditionalOnProperty
 * @date: 2023/4/24 10:20
 **/
@Component
@Slf4j
public class UseConditionalOnProperty {

    @Value("${is_load_bean}")
    private String isLoadBean;

    @Bean
    @ConditionalOnProperty(value = "is_load_bean",havingValue = "true",matchIfMissing = true)
    public void loadBean(){
        log.info("是否加载当前类");
    }

    @Bean
    public void compareLoadBean(){
        log.info("加载bean属性:" + isLoadBean);
    }
}

启动项目时输出打印的日志。如图:

将配置文件的数据信息改成false,则不会打印出结果。

2、ConditionalOnProperty属性与源码

2.1 属性

查看@ConditionalOnProperty源码可以看到该注解定义了几个属性。

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

	/**
	 * name别名,数组类型,获取对应property名称的值,与name不能同时使用
	 */
	String[] value() default {};

	/**
	 * 属性前缀,未指定时,自动以点"."结束,有效前缀由一个或多个词用点"."连接。
     * 如:spring.datasource
	 */
	String prefix() default "";

	/**
	 * 属性名称,配置属性完整名称或部分名称,可与prefix组合使用,不能与value同时使用
	 */
	String[] name() default {};

	/**
	 * 可与name组合使用,比较获取到的属性值与havingValue的值是否相同,相同才加载配置
	 */
	String havingValue() default "";

	/**
	 * 缺少该配置属性时是否加载,默认为false。如果为true,没有该配置属性时也会正常加载;反之则不会生效
	 */
	boolean matchIfMissing() default false;

}

2.2 源码

查看OnPropertyCondition类中国的getMatchOutcome()方法:

@Override
	public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
		//获取所有注解ConditionalOnProperty下的所有属性match,message
        List<AnnotationAttributes> allAnnotationAttributes = annotationAttributesFromMultiValueMap(
				metadata.getAllAnnotationAttributes(ConditionalOnProperty.class.getName()));
		List<ConditionMessage> noMatch = new ArrayList<>();
		List<ConditionMessage> match = new ArrayList<>();
        //遍历注解中的属性
		for (AnnotationAttributes annotationAttributes : allAnnotationAttributes) {
            //创建判定的结果,ConditionOutcome只有两个属性,
			ConditionOutcome outcome = determineOutcome(annotationAttributes, context.getEnvironment());
			(outcome.isMatch() ? match : noMatch).add(outcome.getConditionMessage());
		}
		if (!noMatch.isEmpty()) {
            //如果有属性没有匹配,则返回
			return ConditionOutcome.noMatch(ConditionMessage.of(noMatch));
		}
		return ConditionOutcome.match(ConditionMessage.of(match));
	}

在上述源码中determineOutcome()是关键方法,我们来看看:

private ConditionOutcome determineOutcome(AnnotationAttributes annotationAttributes, PropertyResolver resolver) {
	//初始化
    Spec spec = new Spec(annotationAttributes);
    List<String> missingProperties = new ArrayList<>();
    List<String> nonMatchingProperties = new ArrayList<>();
    //收集属性,将结果赋值给missingProperties,nonMatchingProperties
    spec.collectProperties(resolver, missingProperties, nonMatchingProperties);
    if (!missingProperties.isEmpty()) {
        //missingProperties属性不为空,说明设置matchIfMissing的是false,则不加载类
        return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec)
                .didNotFind("property", "properties").items(Style.QUOTE, missingProperties));
    }
    if (!nonMatchingProperties.isEmpty()) {
        //nonMatchingProperties属性不为空,则设置的属性值与havingValue值不匹配,则不加载类
        return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec)
                .found("different value in property", "different value in properties")
                .items(Style.QUOTE, nonMatchingProperties));
    }
    return ConditionOutcome
            .match(ConditionMessage.forCondition(ConditionalOnProperty.class, spec).because("matched"));
}

Spec是OnPropertyCondition的一个静态内部类,初始化@ConditionalOnProperty中的属性。

private static class Spec {

		private final String prefix;

		private final String havingValue;

		private final String[] names;

		private final boolean matchIfMissing;
        //初始化,给各属性赋值
		Spec(AnnotationAttributes annotationAttributes) {
			String prefix = annotationAttributes.getString("prefix").trim();
			if (StringUtils.hasText(prefix) && !prefix.endsWith(".")) {
				prefix = prefix + ".";
			}
			this.prefix = prefix;
			this.havingValue = annotationAttributes.getString("havingValue");
			this.names = getNames(annotationAttributes);
			this.matchIfMissing = annotationAttributes.getBoolean("matchIfMissing");
		}

        //处理name与value
		private String[] getNames(Map<String, Object> annotationAttributes) {
			String[] value = (String[]) annotationAttributes.get("value");
			String[] name = (String[]) annotationAttributes.get("name");
            //限制了value或name必须指定
			Assert.state(value.length > 0 || name.length > 0,
					"The name or value attribute of @ConditionalOnProperty must be specified");
			//value和name只能有一个存在,不能同时使用
            Assert.state(value.length == 0 || name.length == 0,
					"The name and value attributes of @ConditionalOnProperty are exclusive");
            return (value.length > 0) ? value : name;
		}

		private void collectProperties(PropertyResolver resolver, List<String> missing, List<String> nonMatching) {
			//遍历names,即value或name的值
            for (String name : this.names) {
                //前缀 + name,获取配置文件中key
				String key = this.prefix + name;
                //验证配置属性中包含key
				if (resolver.containsProperty(key)) {
                    //如包含,则获取key对应的值,与havingValue的值进行匹配
					if (!isMatch(resolver.getProperty(key), this.havingValue)) {
                        //不匹配则添加到nonMatching
						nonMatching.add(name);
					}
				}
				else {
                    //验证配置属性中没有包含key,判断是否配置了matchIfMissing属性
					if (!this.matchIfMissing) {
                        //该属性不为true则添加到missing中
						missing.add(name);
					}
				}
			}
		}

		private boolean isMatch(String value, String requiredValue) {
            //验证requiredValue是否有值
			if (StringUtils.hasLength(requiredValue)) {
                //有值,则进行比较,不区分大小写
				return requiredValue.equalsIgnoreCase(value);
			}
            //没有值,则验证value是否等于false
            //这也是为什么name, value不配置值的情况下, 类依然会被加载的原因
			return !"false".equalsIgnoreCase(value);
		}

		@Override
		public String toString() {
			StringBuilder result = new StringBuilder();
			result.append("(");
			result.append(this.prefix);
			if (this.names.length == 1) {
				result.append(this.names[0]);
			}
			else {
				result.append("[");
				result.append(StringUtils.arrayToCommaDelimitedString(this.names));
				result.append("]");
			}
			if (StringUtils.hasLength(this.havingValue)) {
				result.append("=").append(this.havingValue);
			}
			result.append(")");
			return result.toString();
		}

	}

根据业务需求,我们可以实现配置某些属性动态地去加载某些类或方法。

到此这篇关于SpringBoot之@ConditionalOnProperty注解使用方法的文章就介绍到这了,更多相关SpringBoot @ConditionalOnProperty注解内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringBoot用配置影响Bean加载@ConditionalOnProperty

    目录 故事背景 调试&解决 SpringBoot 是怎么做的 故事的最后 故事背景 故事发生在几个星期前,自动化平台代码开放给整个测试团队以后,越来越多的同事开始探索平台代码.为了保障自动化测试相关的数据和沉淀能不被污染,把数据库进行了隔离.终于有了2个数据库实例,一个给dev环境用,一个给test环境用.可是随着平台的发展,越来越多的中间件被引用了.所以需要隔离的东西就越来越多了,比如MQ,Redis等.成本越来越高,如果像数据库实例一样全部分开搞一套,那在当下全域降本增效的大潮下,也是困难重

  • 使用@ConditionalOnProperty控制是否加载的操作

    @ConditionalOnProperty控制是否加载 public interface OSService { void os(); } @ConditionalOnProperty(prefix = "custom.os", name = "name", havingValue = "linux") @Service("osService") public class LinuxService implements OS

  • Spring Boot中@ConditionalOnProperty的使用方法

    前言 在Spring Boot的自动配置中经常看到@ConditionalOnProperty注解的使用,本篇文章带大家来了解一下该注解的功能.下面话不多说了,来一起看看详细的介绍吧. Spring Boot中的使用 在Spring Boot的源码中,比如涉及到Http编码的自动配置.数据源类型的自动配置等大量的使用到了@ConditionalOnProperty的注解. HttpEncodingAutoConfiguration类中部分源代码: @Configuration(proxyBean

  • 关于@ConditionalOnProperty的作用及用法说明

    目录 @ConditionalOnProperty作用及用法 例子1 例子2 @ConditionalOnProperty使用注意事项 @ConditionalOnProperty的功能 使用过程中遇到的问题 解决办法 @ConditionalOnProperty作用及用法 在spring boot中有时候需要控制配置类是否生效,可以使用@ConditionalOnProperty注解来控制@Configuration是否生效. 通过其两个属性name以及havingValue来实现的,其中na

  • 解决SpringBoot的@DeleteMapping注解的方法不被调用问题

    目录 SpringBoot的@DeleteMapping注解的方法不被调用 1.前端代码 2.服务端代码 3.Spring boot源码(重点) 4.配置文件 SpringBoot开发中常用的注解 参数说明如下 总结 SpringBoot的@DeleteMapping注解的方法不被调用 1.前端代码 <!--1 给当前按钮绑定样式deleteBtn 2 给按钮绑定自定义属性--> <button th:attr="del_uri=@{/emp/}+${emp.id}"

  • spring-boot通过@Scheduled配置定时任务及定时任务@Scheduled注解的方法

    串行的定时任务 @Component public class ScheduledTimer { private Logger logger = Logger.getLogger(this.getClass()); /** * 定时任务,1分钟执行1次,更新潜在客户超时客户共享状态 */ @Scheduled(cron="0 0/1 8-20 * * ?") public void executeUpdateCuTask() { Thread current = Thread.curr

  • 基于注解实现 SpringBoot 接口防刷的方法

    该示例项目通过自定义注解,实现接口访问次数控制,从而实现接口防刷功能,项目结构如下: 一.编写注解类 AccessLimit package cn.mygweb.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Targ

  • SpringBoot Shiro 权限注解不起作用的解决方法

    最近在学习springboot结合shiro做权限管理时碰到一个问题. 问题如下: 我在userRealm中的doGetAuthorizationInfo方法中给用户添加了权限,然后在Controller中写了下面的代码.其中URL为/listArticle的方法必须要有article:over权限才能通过.我在doGetAuthorizationInfo方法中给该用户添加的权限并没有article:over,但是当前端向该URL发送请求时,@RequiresPermissions注解不起作用,

  • springboot集成@DS注解实现数据源切换的方法示例

    目录 启用@DS实现数据源切换 POM内添加核心jar包 yml配置 “核心”-使用@DS注解 最后 启用@DS实现数据源切换 POM内添加核心jar包         <dependency>             <groupId>com.baomidou</groupId>             <artifactId>dynamic-datasource-spring-boot-starter</artifactId>        

  • SpringBoot中@ConfigurationProperties注解实现配置绑定的三种方法

    properties配置文件如下: human.name=Mr.Yu human.age=21 human.gender=male 如何把properties里面的配置绑定到JavaBean里面,以前我们的做法如下: public class PropertiesUtil { public static void getProperties(Person person) throws IOException { Properties properties = new Properties();

  • 详解springboot通过Async注解实现异步任务及回调的方法

    目录 前言 什么是异步调用? 1. 环境准备 2. 同步调用 3. 异步调用 4. 异步回调 前言 什么是异步调用? 异步调用是相对于同步调用而言的,同步调用是指程序按预定顺序一步步执行,每一步必须等到上一步执行完后才能执行,异步调用则无需等待上一步程序执行完即可执行.异步调用可以减少程序执行时间. 1. 环境准备 在 Spring Boot 入口类上配置 @EnableAsync 注解开启异步处理.创建任务抽象类 AbstractTask,并实现三个任务方法 doTaskOne(),doTas

  • SpringBoot Bean花式注解方法示例下篇

    目录 1.容器初始化完成后注入bean 2.导入源的编程式处理 3.bean裁定 拓展 4.最终裁定 1.容器初始化完成后注入bean import lombok.Data; import org.springframework.stereotype.Component; @Component("miao") @Data public class Cat { } 被注入的JavaBean import org.springframework.context.annotation.Con

  • SpringBoot使用自定义注解实现权限拦截的示例

    本文介绍了SpringBoot使用自定义注解实现权限拦截的示例,分享给大家,具体如下: HandlerInterceptor(处理器拦截器) 常见使用场景 日志记录: 记录请求信息的日志, 以便进行信息监控, 信息统计, 计算PV(page View)等 性能监控: 权限检查: 通用行为: 使用自定义注解实现权限拦截 首先HandlerInterceptor了解 在HandlerInterceptor中有三个方法: public interface HandlerInterceptor { //

  • springboot下使用mybatis的方法

    使用mybatis-spring-boot-starter即可. 简单来说就是mybatis看见spring boot这么火,于是搞出来mybatis-spring-boot-starter这个解决方案来与springboot更好的集成 详见 http://www.mybatis.org/spring/zh/index.html 引入mybatis-spring-boot-starter的pom文件 <dependency> <groupId>org.mybatis.spring.

随机推荐

其他