SpringBoot(15) — @ComponentScan

2021-08-05  本文已影响0人  奔跑的佩恩

前言

上节文章我们已经了解了IoC批量装配Bean的知识。大家感兴趣的话,可参考
SpringBoot(14) — IoC装配Bean
SpringBootIoC操作中,我们经常会用到注解@ComponentScan,这是一个扫描策略注解。那么,今天我们就来学习下@ComponentScan的详细使用吧。

今天涉及知识有:

  1. 整体理解
  2. basePackages
  3. basePackageClasses
  4. includeFilters & excludeFilters
  5. @Filter 中多个属性使用时的写法
  6. 装配Bean的使用

来波运行结果图:

======我是测试啊=====
======student=====Student(id=1, name=小明同学, age=12)

一. 整体理解
针对以下项目结构:

image.png
上面我们已经知道当@ComponentScan注解在StudentConfig类头部的情况下,则Student必须放置在config/文件夹下才行。但实际开发过程中,我们希望Student可放置的地方更加灵活。由于@ComponentScan默认扫描的是config/文件夹下所有被@Component注解的类,但我在该文件夹下有些被@Component注解的类不想被IoC装配怎么办。下面就来具体讲解。
@ComponentScan 有以下几个常用属性:

其中includeFiltersexcludeFilters的定义都需要借助@ComponentScan.Filter来完成相应的扫描规则。下面对这个几个常用属性一 一 讲解。

二. basePackages

定义扫描包名。basePackages接收的是字符串数组。以上面讲到的config/config_entity/Student路径为例。若需要扫描config/文件夹下所有装配Bean,我们可以这样定义 @ComponentScan :

上一篇 下一篇

猜你喜欢

热点阅读