欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > @ConditionalOnExpression条件加载Bean

@ConditionalOnExpression条件加载Bean

2024/10/23 21:24:59 来源:https://blog.csdn.net/dxjren/article/details/143117503  浏览:    关键词:@ConditionalOnExpression条件加载Bean

@ConditionalOnExpression 是 Spring Framework 中用于条件性加载 Bean 的注解,它允许你基于一个 Spring Expression Language (SpEL) 表达式的结果来决定是否加载某个 Bean。在你的例子中,注解中的表达式依据一个配置属性来决定是否启用相关功能。

注解详解

@ConditionalOnExpression("'${cache.clean.enabled:false}'.equals('true')")

这个注解中的表达式主要做了以下几件事:

  1. ${cache.clean.enabled:false}:这是一个 Spring 配置属性占位符。

    1.1 ${cache.clean.enabled} 表示从配置文件(如 application.properties 或 application.yml)中获取 cache.clean.enabled 的值。
    1.2 如果没有找到 cache.clean.enabled 属性,则使用默认值 false。

  2. 'true'.equals(...):这是一个字符串比较操作,它检查属性值是否为 'true'
    2.1 如果配置属性的值为 'true',表达式结果为 true,则注解标注的 Bean 会被加载。
    2.2 如果配置属性的值不是 ‘true’,则表达式结果为 false,该 Bean 将不会被加载。

示例说明:

假设你在 application.properties 中有以下配置:

cache.clean.enabled=true
相关代码
package cn.keking.config;import cn.keking.service.cache.CacheService;
import cn.keking.utils.KkFileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;/*** @auther: chenjh* @since: 2019/6/11 7:45*/
@Component
@ConditionalOnExpression("'${cache.clean.enabled:false}'.equals('true')")
public class SchedulerCleanConfig {private final Logger logger = LoggerFactory.getLogger(SchedulerCleanConfig.class);private final CacheService cacheService;public SchedulerCleanConfig(CacheService cacheService) {this.cacheService = cacheService;}private final String fileDir = ConfigConstants.getFileDir();//默认每晚3点执行一次@Scheduled(cron = "${cache.clean.cron:0 0 3 * * ?}")public void clean() {logger.info("Cache clean start");cacheService.cleanCache();KkFileUtils.deleteDirectory(fileDir);logger.info("Cache clean end");}
}

那么,@ConditionalOnExpression 中的表达式将解析为 'true'.equals('true'),因此,相关的 Bean 会被加载。

如果没有配置这个属性,默认值是 false,则表达式解析为 'false'.equals('true'),相关的 Bean 不会被加载。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com