@ConditionalOnBean与@ConditionalOnClass

上一篇讲的@Conditional可以通过条件控制是否注入Bean,这篇讲下有关Bean其它几个常用的注解使用方式

@ConditionalOnBean         //	当给定的在bean存在时,则实例化当前Bean
@ConditionalOnMissingBean // 当给定的在bean不存在时,则实例化当前Bean
@ConditionalOnClass // 当给定的类名在类路径上存在,则实例化当前Bean
@ConditionalOnMissingClass // 当给定的类名在类路径上不存在,则实例化当前Bean

下面我通过案例深入讲下@ConditionalOnBean 注解,这个理解其它也就理解了。

一、@ConditionalOnBean概念

需求场景 比如下面一种场景,我在实例化People对象的时候,需要注入一个City对象。这个时候问题来了,如果city没有实例化,那么下面就会报空指针或者直接报错。

所以这里需求很简单,就是当前city存在则实例化people,如果不存在则不实例化people,这个时候@ConditionalOnBean 的作用来了。

    @Bean
public People people(City city) {
//这里如果city实体没有成功注入 这里就会报空指针
city.setCityName("千岛湖");
city.setCityCode(301701);
return new People("小小", 3, city);
}

1、@ConditionalOnBean注解定义

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnBeanCondition.class)
public @interface ConditionalOnBean {
/**
* 需要作为条件的类的Class对象数组
*/
Class<?>[] value() default {};
/**
* 需要作为条件的类的Name,Class.getName()
*/
String[] type() default {};
/**
* (用指定注解修饰的bean)条件所需的注解类
*/
Class<? extends Annotation>[] annotation() default {};
/**
* spring容器中bean的名字
*/
String[] name() default {};
/**
* 搜索容器层级,当前容器,父容器
*/
SearchStrategy search() default SearchStrategy.ALL;
/**
* 可能在其泛型参数中包含指定bean类型的其他类
*/
Class<?>[] parameterizedContainer() default {};
}

下面举例说明。

二、@ConditionalOnBean示例

1、Bean实体

1)City类

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class City {
/**
* 城市名称
*/
private String cityName;
/**
* 城市code
*/
private Integer cityCode;
}

2)People类

这里City作为People一个属性字段。

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class People {
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private Integer age;
/**
* 城市信息
*/
private City city;
}

2、Config类

这里写个正常的配置类,City成功注入到IOC容器中。

@Slf4j
@Configuration
public class Config {
@Bean
public City city() {
City city = new City();
city.setCityName("千岛湖");
return city;
}
@Bean
public People people(City city) {
//这里如果city实体没有成功注入 这里就会报空指针
city.setCityCode(301701);
return new People("小小", 3, city);
}
}

3、Test测试类

@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class TestConditionOn { @Autowired(required=false)
private People people; @Test
public void test() {
System.out.println("= = = = = = = = = = = = = ");
System.out.println("people = " + people);
System.out.println("= = = = = = = = = = = = = ");
}
}

运行结果

一切正常,这个很符合我们实际开发中的需求。但是如果有一种情况,就是我的city并没有被注入。我把上面这部分注视掉。

//    @Bean
// public City city() {
// City city = new City();
// city.setCityName("千岛湖");
// return city;
// }

再运行测试类

发现启动直接报错了,这当然不是我们希望看到的,我们是要当city已经注入那么实例化people,如果没有注入那么不实例化people。

@Slf4j
@Configuration
public class Config {
// @Bean
// public City city() {
// City city = new City();
// city.setCityName("千岛湖");
// return city;
// } /**
* 这里加了ConditionalOnBean注解,就代表如果city存在才实例化people
*/
@Bean
@ConditionalOnBean(name = "city")
public People people(City city) {
//这里如果city实体没有成功注入 这里就会报空指针
city.setCityCode(301701);
return new People("小小", 3, city);
}
}

再运行测试类

很明显,上面因为city已经注释调,所以也导致无法实例化people,所以people为null。

注意有点要注意的,就是一旦使用@Autowired那就默认代表当前Bean一定是已经存在的,如果为null,会报错。所以这里要修改下。

@Autowired(required=false) //required=false 的意思就是允许当前的Bean对象为null。

总结讲了这个注解,其它三个注解的意思大致差不多,在实际开发过程中可以根据实际情况使用该注解。

GitHub源码 https://github.com/yudiandemingzi/spring-boot-study

项目名称 04-conditionalon

只要自己变优秀了,其他的事情才会跟着好起来(中将4)

SpringBoot(16)—@ConditionalOnBean与@ConditionalOnClass的更多相关文章

  1. springboot的@ConditionalOnBean注解

      上篇文章中分析了springboot的自动注入的原理,可在文章后面的推荐阅读中温习哦.在自动注入的原理那篇文章中提到了@ConditionalOnXX注解,今天来看下springboot中的@Co ...

  2. java框架之SpringBoot(16)-分布式及整合Dubbo

    前言 分布式应用 在分布式系统中,国内常用 Zookeeper + Dubbo 组合,而 SpringBoot 推荐使用 Spring 提供的分布式一站式解决方案 Spring + SpringBoo ...

  3. springboot的@ConditionalOnClass注解

    大家好,我是"良工说技术". 今天给大家带来的是springboot中的@ConditionalOnClass注解的用法.上次的@ConditionalOnBean注解还记得吗? ...

  4. 【springboot】知识点总结

    [springboot 基础编] 01.SpringBoot>01 - 第一个应用–HelloWorld 02.SpringBoot>02 - 整合 MyBatis 03.SpringBo ...

  5. Spring @Conditional简单使用 以及 使用时注意事项一点

    @Conditional注解在类的方法中 @Conditional注解失效的一种原因 @Conditional注解在类上 手写的低配版@ConditionalOnClass Spring  @Cond ...

  6. 006-Spring Boot自动配置-Condition、Conditional、Spring提供的Conditional自动配置

    一.接口Condition.Conditional(原理) 主要提供一下方法 boolean matches(ConditionContext context, AnnotatedTypeMetada ...

  7. Spring Boot 自动配置之@Conditional的使用

    Spring Boot自动配置的"魔法"是如何实现的? 转自-https://sylvanassun.github.io/2018/01/08/2018-01-08-spring_ ...

  8. Spring Cloud系列之Commons - 1. 背景与基础知识准备

    本文基于 Spring Cloud 2020.0 发布版的依赖 本系列会深入分析 Spring Cloud 的每一个组件,从Spring Cloud Commons这个 Spring Cloud 所有 ...

  9. java日常开发必备:list的四种遍历

      在平时的开发过程中使用List的场景很多,你知道List的遍历有多少种方式?今天一起来梳理下List的几种遍历方式.这里以java.util.ArrayList为例来演示.   这里有一个最简单的 ...

随机推荐

  1. 运行java可执行jar包

    导出与导入:如果要用别的项目的类, 把对方类export出成jar包(多个类的集合),然后复制到自己项目路径下然后添加至构建路径,jar包右键buildpath/addtobuildpath.expo ...

  2. typescript与nodejs(二)基于装饰器实现路由表

    之前实现了一个简单的WebServer 但是这离实际使用还有一点距离 webserver 首先面对第一个问题是路由表 啥是路由表 路由表别看听起来神秘,但是其实就是 if else onhttp- { ...

  3. [译]Vulkan教程(04)基础代码

    [译]Vulkan教程(04)基础代码 General structure 通用结构 In the previous chapter you've created a Vulkan project w ...

  4. C#_.NetFramework_Web项目_EXCEL数据导出

    [推荐阅读我的最新的Core版文章,是最全的介绍:C#_.NetCore_Web项目_EXCEL数据导出] 项目需引用NPOI的NuGet包: A-2:EXCEL数据导出--Web项目--C#代码导出 ...

  5. C# 使用WM_COPYDATA传输数据(两个窗体间通信)

    //发送方 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data ...

  6. python distutils 基本打包与发布

    distutils 实现对package 包的发布 import math def showMsg(a): return a * a * a a = 10 print('%d 的三次方是 %d' % ...

  7. js基本操作

    js操作页面三步骤 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> < ...

  8. Python进阶二

    文章目录 函数参数1.位置传递2.名称传递 def f(a,b): f(1,2) f(b=2,a=1) 3.可选参数传递(可选参数必须放在最后)def f(a,b=1) ✔def f(b=1,a) ❌ ...

  9. mysql安装及简单操作

    sudo grep mysql_root_passwd /root/env.txt (现在很多人开始使用云主机,登录云主机之后可以根据该命令查看阿里云数据库密码) mysql 安装:rpm+retha ...

  10. ramdisk配置、解压、创建rootfs、启动简单分析

    关键词:ramdisk.rdint..init.ramfs.__initramfs_start.__initramfs_size.rootfs.ramfs.populate_rootfs().gzip ...