springBoot----@ConditionalOnxxx相关注解总结

SpringBoot条件注解:@ConditionalOnClass等注解的使用场景 对于频繁使用的条件组合,可以创建自定义的组合注解,提高代码的可读性和可维护性。/*** 自定义组合条件注解*//*** 使用自定义组合条件注解*/@Bean通过这种方式,可以将复杂的条件逻辑封装在一个注解中,使代码更加简洁清晰。SpringBoot的条件注解体系提供了强大而灵活的机制,使配置能够根据运行环境、依赖情况和配置属性等条件动态调整。@ConditionalOnClass等注解在自动配置和可插拔功能实现中发挥着重要作用,使得应用能够自适应地调整其行为和功能。 阅读详情

转载:https://www.cnblogs.com/yixianyixian/p/7346894.html

  • @ConditionalOnClass:该注解的参数对应的类必须存在,否则不解析该注解修饰的配置类;
  • @ConditionalOnMissingBean:该注解表示,如果存在它修饰的类的bean,则不需要再创建这个bean;可以给该注解传入参数例如@ConditionOnMissingBean(name = "example"),这个表示如果name为“example”的bean存在,这该注解修饰的代码块不执行。

@ConditionalOnClass:该注解的参数对应的类必须存在,否则不解析该注解修饰的配置类;

 

下面来介绍如何使用@Condition

 

[html] view plain copy

 

  1. public class TestCondition implements Condition    
  2. {    
  3.     /**   
  4.      * 只有返回true,才会启用配置   
  5.      */    
  6.     public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata)    
  7.     {    
  8.         return true;    
  9.     }    
  10. }  

 

 

 

@Conditional(TestCondition.class)

这句代码可以标注在类上面,表示该类下面的所有@Bean都会启用配置,也可以标注在方法上面,只是对该方法启用配置。

 

spring框架还提供了很多@Condition给我们用,当然总结用语哪种好理解,看给位读者喽

@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
@ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
@ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
@ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
@ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)
@ConditionalOnNotWebApplication(不是web应用)

后续会继续补充

另一种总结

@ConditionalOnClass:该注解的参数对应的类必须存在,否则不解析该注解修饰的配置类;
@ConditionalOnMissingBean:该注解表示,如果存在它修饰的类的bean,则不需要再创建这个bean;可以给该注解传入参数例如@ConditionOnMissingBean(name = "example"),这个表示如果name为“example”的bean存在,这该注解修饰的代码块不执行。

 

接上文

condition自定义声明

复制代码

public class InitConditional implements Condition{

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        //判断是否已经包含了amazonTest Bean
        Boolean bol =  conditionContext.getBeanFactory().containsBean("amazonTest");
        return bol;
    }
}

复制代码

使用自定义的Conditional

复制代码

@Component
@Conditional(InitConditional.class)
public class AmazonTest {

    @Autowired
    private AmazonProperties amazonProperties;

    public void testGet(){
        System.out.println("    testGet Associated");
        System.out.println(amazonProperties.getAssociateId());
    }
}

复制代码

WelcomeController 与 AmazonTest关联,使用ConditionOnBean(如果条件的bean存在,当前的bean才会被声明)

复制代码

@Component
@ConditionalOnBean(AmazonTest.class)
public class WelcomeController {
    private static final Logger logger = LoggerFactory.getLogger(WelcomeController.class);

    private AppProperties app;
    private GlobalProperties global;

    @Autowired
    public void setApp(AppProperties app) {
        this.app = app;
    }

    @Autowired
    public void setGlobal(GlobalProperties global) {
        this.global = global;
    }

    public void testWelcome(){
        String appProperties = app.toString();
        String globalProperties = global.toString();
        System.out.println(appProperties);
        System.out.println(globalProperties);
    }
}

复制代码

main测试文件入口

复制代码

public static void main(String[] args) {
        ConfigurableApplicationContext configurableApplicationContext =SpringApplication.run(DemoApplication.class, args);
        //bean自动注册,根据bean的名字获取Bean
        AmazonProperties amazonProperties = (AmazonProperties) configurableApplicationContext.getBean("amazonProperties");
        System.out.println(amazonProperties.getAssociateId());



        Boolean aBooleanWelcomeController = configurableApplicationContext.containsBean("welcomeController");
        if(!aBooleanWelcomeController){
            System.out.println("        welcomeController init fail");
        }else{
            WelcomeController welcomeController = (WelcomeController) configurableApplicationContext.getBean("welcomeController");
            System.out.println("        welcomeController init Success");
        }


        Boolean    aBooleanAmazonTest = configurableApplicationContext.containsBeanDefinition("amazonTest");
        if(!aBooleanAmazonTest){
            System.out.println("        amazonTest init fail");
        }else{
            AmazonTest amazonTest = (AmazonTest) configurableApplicationContext.getBean("amazonTest");
            System.out.println("        amazonTest init Success");
        }
}

复制代码

@ConditionalOnClass和@ConditionalOnBean的作用和使用方式,以及两者的区别 ConditionalOnClass 注解是 Spring Boot 中的一个条件注解,用于根据类路径中是否包含指定的类来决定是否加载一个 Bean 或配置类。这个注解可以用于在特定条件下控制 Bean 或配置类的加载行为。 阅读详情

相关推荐

ConvLSTM时空预测实战代码详解

ConvLSTM代码复现

JaysonWong的博客 1万+

@ConditionalOnClass注解分析

Spring中为Kafka提供了一个自动配置类 KafkaAutoConfiguration 在类上有一个注解 @ConditionalOnClass(KafkaTemplate.class) 这个注解通俗的说就是Spring工程中引用了Kafka的包 才会构建这个bean 官方解释: /** * {@link Conditional} that only matches wh...

雪落南城的博客 10万+

PyTorch版Unet训练后别只看loss:手把手教你计算并可视化多类别语义分割的mIoU(附完整代码)

本文详细介绍了在PyTorch中使用Unet模型进行多类别语义分割后,如何计算和可视化mIoU(mean Intersection over Union)以全面评估模型性能。通过完整的代码示例和实用技巧,帮助开发者从loss优化转向更精准的区域分割评估,特别适用于医学图像分析等关键场景。

weixin_30906185的博客 435

spring源码 - 条件注解@ConditionnalOnClass的原理分析

用过springboot的小伙伴们都知道,相比于spring,它最大的优势是帮我们省去了一大堆超大一堆繁琐的配置。比如在spring中,当我们需要在项目中整合第三方插件(如redis、mybatis、rabbitmq)时,往往需要在xml配置文件中去配置这些插件的等将其与spring进行整合。而在springboot中,他会根据项目中引入哪些插件自动地将插件进行整合,这都得益于springboot的自动装配或称为自动配置。

理想万岁万万岁的博客 5802

200_matlab处理NCEP数据并画全球彩色的风场图

200_matlab处理NCEP数据并画全球彩色的风场图。

miaobo0的博客 1240

从Reset到Read:深入解析Rolling Shutter曝光流水线

本文深入解析Rolling Shutter(卷帘曝光)的工作原理,重点探讨Reset和Read信号在图像传感器中的关键作用。通过Reset-Read流水线机制,详细解释了曝光控制、时序调优及运动伪影补偿等核心技术,帮助读者理解卷帘曝光在高速摄影和动态场景中的应用。

weixin_42531925的博客 254

@ConditionalOnClass注解详解

在类路径下存在某个类时才会实例化加ConditionalOnClass注解类的bean。

lp1302190871的博客 2519

游程理论提取灾害事件特征V2---基于MATLAB语言的编程实现

游程理论,灾害事件,MATLAB

EWBA_GIS_RS_ER的博客 3793

spring boot @ConditionalOnxxx相关注解总结

下面来介绍如何使用@Condition public class TestCondition implements Condition { /** * 只有返回true,才会启用配置 */ public boolean matches(ConditionContext context, AnnotatedTypeMetadata metada...

臣本布衣,躬耕于南阳 4万+

SAP Single Sign-On 全景指南:从传统 SAP SSO 到 SAP Secure Login Service for SAP GUI 的架构、场景与迁移实践

本文系统梳理了SAP生态下的单点登录技术方案,重点分析了SAP GUI的云化替代方案SAP Secure Login Service(SLS)。内容涵盖SNC、Kerberos/SPNEGO、SAML 2.0等核心协议的技术实现,对比了传统SAP SSO与新型SLS for SAP GUI的架构差异,并给出AS ABAP系统的具体实施路径。针对SAP GUI访问、浏览器访问Fiori/移动端等不同场景,提供了详细的协议选型建议和配置指南,帮助团队构建安全可靠且适应云时代的统一认证体系。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 273

【ESD专题】从原理上分析TVS管PCB Layout的经验法则

我们常常会听到的一些经验法则,按这些经验法则去做,一般也不会有什么问题,但是到底是为什么呢? 没有从原理上分析和证明的时候,往往在Layout之后还要担心实际测试结果怎么样。或是在实际测试出问题后,根本无法进行分析,难道说修改一个版本就好了?那要从哪里修改呢?也无从下手呀。...

一点硬件 1446

【spring boot】spring boot @ConditionalOnxxx相关注解总结

参考地址:https://blog.youkuaiyun.com/win7system/article/details/54377471 使用场景:在自动解析封装配置文件中的配置完成自动注入spring的时候       例如rocketMQ相关配置        例如Druid相关配置  ...

weixin_34289744的博客 160

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Springboot-注册注解【springboot常用注解】

使用@EnableConfigurationProperties会把属性与组件绑定,并且还会自动将组件放到容器中./一般用于第三方写好的组件进行属性绑定,springboot默认只扫描主程序所在的包.也可以将组件类名上方的@component取消掉,直接在配置类中注册组件也是可以的。将容器中任意组件(Bean)的属性值和配置文件的配置项的值进行绑定。第三步: 查看是否注册成功,在主程序中,查看容器中是否有这些组件。第二步:创建一个配置类,并且注册相应的组件,我创建的类名为。第三步:在配置类中配置。

qq_35653657的博客 942

深度学习工具包 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")

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

【SpringBoot】自动装配原理

【SpringBoot】自动装配原理

junR_980218的博客 283

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

spring boot常用注解

SpringBoot注解 @SpringBootApplication: 开启Spring Boot自动配置的核心注解,相关等同于@Configuration,@EnableAutoConfiguration和@ComponentScan三个注解同时使用。 @EnableAutoConfiguration:SpringBoot自动配置开启注解。开启之后,会尝试根据添加到classpath中jar依赖自动配置相关组件。是Spring Boot自动配置机制的核心注解之一。 @ConditionalOnXXXX:

cx201125的博客 279
上一篇: p6spy使用
下一篇: class is not public in my package and cannot be accessed from outside package
琅琊山二当家
博客等级 码龄18年 447粉丝 322原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值