@ComponentScan 回顾

一、最近使用

因为 @SpringBootApplication 已经集成了它,平时就不怎么用。

最近在搭建项目框架,

使用的 maven 子模块

@SpringBootApplication 在boot模块中。

主要业务代码在另外两个子模块中。

项目启动时发现, 只启动了boot模块。两外两个模块未启动。

查找原因发现,是因为项目路径。

@SpringBootApplication 启动文件在 com.iot.rule 文件夹下。

而两个子模块的默认扫描文件路径是 :com.iot.flow 和 com.iot.forard

 

 

 

 

 

解决办法:添加 Config 文件。

添加 @ComponentScan("com.iot"),扫描 com.iot 下的包。 启动成功。

/** * @author wgy * @version 1.0 * @description 启动自动扫描地址 * @date 2021/3/11 17:27 */ @Configuration @ComponentScan("com.iot") public class Config { }

 

二、 @ComponentScan 的知识点回顾

该注解默认会扫描该类所在包下所有 配置类,相当于之前的 <context:component-scan>

 

2.1 : @ComponentScan 的参数

value : 指定要扫描的包

excludeFilters : 按照规则排除某些包的扫描

includeFilters : 按照规则只包含某些包的扫描

 

@ComponentScan(value = "com.iot", includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Component.class})})

 

type = FilterType.ANNOTATION 是通过注解来过滤。

配置后: 在spring扫描时,跳过 com.iot 下所有被 @Component 注解标注的类。

 

@ComponentScan(value = "com.iot", includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Component.class})}, useDefaultFilters = false )

配置后: 在spring扫描时,只扫描 com.iot 下所有被 @Controller 注解标注的类。

useDefaultFilters = false , 由于 useDefaultFilters 默认为 true, spring 默认会自动发现 @Component 、@Repository、@Service 和 @Controller 注册的类。禁用后再去实现 includeFilters 。

 

2.2 :jdk 8 中, @ComponentScan 要和 @Configuration 一起使用才能起作用。

 

2.3 :@ComponentScans 可以 添加多个 @ComponentScan 实现多个扫描规则。

@Configuration @ComponentScans( value = { @ComponentScan(value = "com.iot.forward"), @ComponentScan(value = "com.iot.flow") } ) public class Config { }

 

posted @ 2021-03-12 17:22  currentTimeMillis  阅读(85)  评论(0编辑  收藏  举报