@ConditionalOnProperty详细理解和使用

深入理解Spring Boot @ConditionalOnProperty:原理、实战与排查指南 在Spring Boot的自动配置体系中,条件注解是控制Bean装配与模块启停的关键机制。开发者常借助@ConditionalOnProperty管理功能开关,但前缀拼写、havingValue语义、matchIfMissing行为等细节,往往导致配置不生效或线上任务重复执行。该注解基于Environment属性评估,将装配决策从业务代码上移到容器层,适用于功能开关、组件选型、starter默认行为等场景。理解其匹配规则与排查链路(如条件评估日志、配置源优先级)是规避空指针与资源浪费的必备技能。本文结合实战 阅读详情

        在Spring应用程序开发的过程中,可能需要根据配置属性的存在和值有条件地创建一些bean,@ConditionalOnProperty注解用于仅在环境属性存在且具有特定值时才启用 bean 注册。

注解源码

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional({OnPropertyCondition.class})
public @interface ConditionalOnProperty {
//获取对应property名称的值,与name不可同时使用
    String[] value() default {};

//配置属性名称的前缀
    String prefix() default "";

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

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

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

value以及 prefix + name 决定属性值(Property Value),以下为匹配规则

解析:假如havingValue为空,

          属性值为boolean类型,则属性值为true 加载该bean,属性值为false 不加载该bean。

           如果属性值不为boolean类型,则有该属性 则加载bean,没有该属性则不加载。

示例

 属性值不是boolean类型的情况

@Bean(name = "emailNotification")
@ConditionalOnProperty(prefix = "notification", name = "service")
public NotificationSender notificationSender() {
    return new EmailNotification();
}

        如果配置该属性则加载:

        notification.service=email

 属性值为boolean类型

@Bean(name = "emailNotification")
@ConditionalOnProperty(prefix = "notification", name = "enable")
public NotificationSender notificationSender() {
    return new EmailNotification();
}

        

如果配置为true则加载

notification.enable=true

如果缺失或为false则不加载

深入理解Spring Boot @ConditionalOnProperty:配置驱动的条件装配与避坑指南 在Spring Boot自动配置体系中,条件注解是决定Bean是否加载的核心机制,而@ConditionalOnProperty则是其中面向配置属性的关键一员。它通过prefix、name、havingValue与matchIfMissing等属性,让应用能够依据外部配置动态决定装配逻辑,从而实现功能开关、多实现切换与自动配置兜底等常见工程需求。但正是这些看似简单的属性,在实际项目中往往隐藏着配置路径拼接错误、matchIfMissing误用导致默认实现覆盖生产配置、多实现同时匹配引发注入冲突等陷阱。本文以 阅读详情

相关推荐

@ConditionalOnProperty使用

Spring boot 中有时候需要控制配置是否生效,使用 @ConditionalOnProperty 注解来控制 @Bean 是否生效。prefix : 是配置前缀,可有可无。name : 是配置名称。完整名称或部分名称,与 prefix 配合使用,与 value 不可同时使用。havingValue : 对比值,与name组合使用,该值与配置中值相同,则配置生效,不相同则配置不生效。matchIfMissing : 缺省值,缺少配置时,是否可以加载。

蔡定努 1377

【Spring】@ConditionalOnProperty 注解的简单使用与介绍

@ConditionalOnProperty注解是Spring Boot的条件注解,主要用法是根据配置文件中的属性来控制某个配置类是否生效,或者控制某个Bean是否被创建。

杜小舟的博客 5153

Spring或SpringBoot中的@ConditionalOnProperty、@ConditionalOnMissingBean、@ConditionalOnExpression及SPI作用

Spring容器加载注册JavaBen的时候,如果在同一个 @Configuration或@Component 标注的配置类中配置多个BeanId相同的实例,那么Spring容器默认只加载第一个同名的实例,在实际应用中需要注意这一点。【1】我们可以将需要条件限制的类当做自动装配类,这样在注册Bean阶段可以保证在我们限制的类注册进容器之前、让被限制的实例先完成注册入容器中,1、因为在实际的应用过程中,我们使用第三方插件,他们的默认配置都会存在于插件的jar包中,而我们的自定义的配置类则在于自身的应用中。

hkl_Forever的博客 1959

ConditionalOnProperty注解的用法

@ConditionalOnProperty注解的用法 @ConditionalOnProperty注解是控制被注解的类中其他注解是否生效。 注意:博主自己只能保证对@Component和@Configuration两个注解有效,其他注解是否有效,需要使用者自己测试了,如果其他有效,还望使用者私信告诉博主,好进行更新! /* prefix:表示配置文件中的前缀(也就是配置文件中第一个点之前的单词) name:表示配置文件中的实际名称(也就是配置文件中第一个点之后的单词) havingValue:表示获

zhangruilinmoo 1059

Spring Boot中@ConditionalOnProperty的使用方法

主要给大家介绍了关于Spring Boot中@ConditionalOnProperty的使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者使用Spring Boot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧

Hi3516CV610开发板实战:从零搭建智能视觉监控系统

本文详细介绍了从零开始基于Hi3516CV610开发板搭建智能视觉监控系统的完整实战流程。涵盖硬件连接、系统配置、摄像头集成、网络设置、固件烧录到视频处理与智能分析功能开发,提供了丰富的实践经验和调试技巧,帮助开发者快速掌握嵌入式视觉系统开发。

vvv99的博客 566

@ConditionalOnProperty注解理解

简单解释一下今天遇到的一个注解 @ConditionalOnProperty(name = “”, havingValue = “”) 我们进入注解看看注解是怎么实现的: @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) @Documented @Conditional(OnP...

追梦赤子的博客 2073

Lmcache+vllm——KVcache卸载CPU/SSD探索

目前查看了vllm、Nvidia dynamo、mooncake都没有找到将kvcache卸载到SSD的方法,幸好lmcache支持。以下进行lmcache+vllm实践,对比将kvcache分别卸载到CPU-ram和SSD上的TTFT性能差异。目前的query只是单并发,对比的效果已经比较明显了,可能多并发下对存储的要求就会更高了。

weixin_43579058的博客 2657

@ConditionalOnProperty的简单理解与使用

@ConditionalOnProperty注解控制组件是否注入spring的注解

L'Étranger的博客 1354

用迅为RK3588开发板DIY无人机飞控:从电路设计到PID调参全记录

本文详细记录了使用迅为RK3588开发板DIY无人机飞控的全过程,从硬件选型、PCB设计到实时系统构建和PID调参。RK3588核心板凭借其强大的AI算力和丰富接口,成为高性能无人机控制解决方案的理想选择。文章还分享了视觉导航系统集成和实际飞行测试经验,为硬件爱好者提供实用参考。

weixin_29053577的博客 436

手把手教你完成基于YOLOv8的水果/商品/食堂/蔬菜/饮料/书籍识别与计价系统,前台+后台管理系统

手把手教你完成基于YOLOv8的商店的水果/商品/食堂/蔬菜/饮料/书籍识别与计价系统,前台+后台管理员系统,可进行目标检测的操作和展示,实现对图片、视频和摄像头的实时目标检测

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 2459

深入理解Spring Boot中的@ConditionalOnProperty注解及其应用

注解是Spring框架提供的注解的扩展,它根据配置属性的存在和值来决定是否创建Bean。默认情况下,如果指定的属性被定义且不等于false,则条件匹配成功。如果你需要更进一步自定义Spring MVC的行为,你可以实现接口,并在你的配置类中重写相应的方法。这允许你添加拦截器、资源处理器、消息转换器等,而不会替换掉Spring Boot的自动配置。如果你想要完全控制Spring MVC的配置,你可以使用注解。这将禁用Spring Boot的MVC自动配置,并允许你手动配置Spring MVC所需的所有组件。

apple_64847327的博客 1416

【虚幻引擎UE】UE5 阴影异常与优化

【虚幻引擎UE】UE5 阴影异常与优化解决方案合集

灵境引路人 3万+

SpringBoot教程(7) @ConditionalOnProperty 详细讲解和示例

@ConditionalOnProperty 详细讲解和示例一、@ConditionalOnProperty简介二、详细代码示例1. 配置文件中配置2. 指定prefix+name3. 只指定name 或者 value3. 指定了havingValue4. 配置项是false,havingValue = false"5. 配置项是false,不设置havingValue6. 缺少配置,但配置了matchIfMissing = true 一、@ConditionalOnProperty简介 在开发基于Spri

Java Spring Elasticsearch 3万+

ROS2入门到精通—— 2-9 ROS2实战:Nav2常见的工程问题(参考3D视觉工坊)

本文介绍了Nav2常见的工程问题,还有调试DWB的一些经验,以及DWB的一些缺点

BigDavid123的博客 1075

【论文解读--Xdog】新型电驱式四足机器人研制与测试

系列文章目录 提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 TODO:写完再整理 文章目录系列文章目录前言一、四足机器人体型大小和驱动方式的比较二、四足机器人设计一些重要的结论三、系统控制框架四、系统硬件框架五、力位混合控制(阻抗控制)六、侧向平衡控制(和VMC如出一辙)七、电机驱动系统研制(FOC磁场定向控制)总结 前言 认知有限,望大家多多包涵,有什么问题也希望能够与大家多交流,共同成长! 本文先对新型电驱式四足机器人研制与测试做个简单的介绍,具体内容后续再更,其他模块可以参

qq_35635374的博客 3730

@ConditionalOnProperty注解详解

1.注解作用 标注@Configuration标注的配置类是否加载 2.注解属性详解 prefix 数组,获取property名称的前缀,可有可无 name 数组,property完整名称或部分名称,与prefix组合使用组成完整属性名称,与value不可同时存在 value 数组,获取property完整名称或部分名称,与prefix组合使用成完整属性名称,与name不可同时存在 having...

OceanSky的专栏 4562

51-14 Retentive Network,RetNet 多尺度保留机制序列建模论文精读

RetNet 提出了多尺度保留机制序列建模,该机制支持三种计算范式,即并行、循环和分块循环。RetNet有更好的全局注意力建模、高效的计算效率、对遮挡的鲁棒性、支持基于注意力的图像生成、与置信度相关的门控机制和多任务学习等特点,对不同视觉任务可以共享历史注意力记忆,可以同时进行分类、分割、检测等任务。RetNet在视觉领域应该有广阔的应用前景。

AIgraphX 1617

SpringBoot - @ConditionalOnProperty注解使用详解

在开发基于SpringBoot框架的项目时,会用到下面的条件注解,有时会有需要控制配置类是否生效或注入到Spring上下文中的场景,可以使用@ConditionalOnProperty注解来控制@Configuration的注解是否生效。

记录并分享 8039

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Spring Boot2.x系列教程(一)@ConditionalOnProperty使用详解

在Spring Boot的自动配置中经常看到@ConditionalOnProperty注解的使用,本篇文章带大家来了解一下该注解的功能。 Spring Boot中的使用 在Spring Boot的源码中,比如涉及到Http编码的自动配置、数据源类型的自动配置等大量的使用到了@ConditionalOnProperty的注解。 HttpEncodingAutoConfiguration类中部分源代码: @Configuration(proxyBeanMethods = false) @EnableConfi

Zshow 的专栏 649

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Spring Boot控制Configuration是否生效之@ConditionalOnProperty

Spring boot中@ConditionalOnProperty能够控制某个configuration是否生效。具体操作是通过其两个属性name以及havingValue来实现的,其中name用来从application.properties或者yml文件中读取某个属性值,如果该值为空,则返回false;如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否...

老刀 5166

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

如何让你的 Starter 组件“听话”? @ConditionalOnProperty 了解一下

是 Spring Boot 自动配置的“基石”之一。它通过将配置加载与属性文件紧密联动,为我们提供了一种极其简单而强大的方式来构建灵活、可配置、可开关的组件。

郑龙飞 856

springboot在配置文件中设置特定功能的启用和停用@ConditionalOnProperty()

场景: 有时候我们需要在生产和开发环境对某个功能进行不同的设置。例如定时功能@EnableScheduling ,我们希望在测试环境禁用定时自动处理,在生产环境启用,这时候就可以用到这个设置 实现: 创建配置类,增加 @ConditionalOnProperty(prefix = "enable", name = "scheduled", havingValue = "true") 注解 @Configuration @EnableScheduling //启用定时任务 //配置文..

goxingman的博客 1696

SpringBoot @ConditionalOnProperty注解

通过属性值来控制Configuration。类似的注解有@ConditionalOnClass, @ConditionalOnBean,@ConditionalOnMissingbean 以@ConditionalOnProperty()为例 @ConditionalOnProperty()的参数: prefix:前缀 name:属性名 havingValue:属性的值 matchIfMissing:value没有匹配,是否启用configuration,默认不启用 没有前缀(prefix)时,匹配单一属性

这就是快乐嘛 348

@ConditionalOnProperty的妙用

@ConditionalOnProperty

Promise_J_Z 1325
上一篇: 策略模式详解
下一篇: Eureka客户端源码分析
思维的深度
博客等级 码龄11年 2万+粉丝 391原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值