SpringBoot - @ComponentScan注解使用详解

【Spring注解驱动开发】自定义TypeFilter指定@ComponentScan注解的过滤规则(1) 如果实现自定义规则进行过滤时,自定义规则的类必须是org.springframework.core.type.filter.TypeFilter接口的实现类。例如,按照自定义规则进行过滤,首先,我们需要创建一个org.springframework.core.type.filter.TypeFilter接口的实现类MyTypeFilter,如下所示。@Override。 阅读详情

写在前面

SpringBoot - @Configuration注解使用详解
SpringBoot - 向容器中注册组件的方法有哪些?
SpringBoot - 如何查看Spring上下文中加载的Bean

@ComponentScan注解的作用是什么?

@ComponentScan主要用于将指定包路径下的、带有特定注解的对象自动装配到Spring容器中。ComponentScan会把正确标注@Component注解的对象进行自动装配。除了@Component外,还有@Controller、@Repository、@Service也标注了@Component注解。
简单来讲:在Spring中通过定义bean的注解定义了一些bean,而Spring并不知道除非你告诉它去可以找到它们,而@ComponentScan的作用就是告诉Spring去哪个路径下可以找到这些bean。

@ComponentScan注解如何使用?

@ComponentScan注解可以定义在接口、类、枚举、注解上。有以下几个常用属性:

  • [1] basePackages:定义待扫描的包路径名
  • [2] basePackageClasses:定义待扫描的类名
  • [3] includeFilters: 满足过滤器条件的,才能被扫描
  • [4] excludeFilters:满足过滤器条件的,不会被扫描

注意:includeFilters和excludeFilters都需要借助@ComponentScan.Filter来完成相应的扫描规则,FilterType有以下几个可选项:

  • [1] ANNOTATION(默认注解类型)
  • [2] ASSIGNABLE_TYPE(指定固定类)
  • [3] ASPECTJ(ASPECTJ类型)
  • [4] REGEX(正则表达式)
  • [5] CUSTOM(自定义类型),自定义的Filter需要实现TypeFilter接口
@ComponentScan(
    includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Service.class})},
    excludeFilters = {@ComponentScan.Filter(type = FilterType.CUSTOM, classes = MyExcludeFilter.class)}
)

@ComponentScan源码分析

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {

	// 指定扫描包路径的位置,可以是单个路径或路径数组
	@AliasFor("basePackages")
	String[] value() default {};

	// 指定扫描包路径的位置,可以是单个路径或路径数组
	@AliasFor("value")
	String[] basePackages() default {};

    // 指定具体的扫描的类
	Class<?>[] basePackageClasses() default {};

	/**
	 * The {@link BeanNameGenerator} class to be used for naming detected components
	 * within the Spring container.
	 * <p>The default value of the {@link BeanNameGenerator} interface itself indicates
	 * that the scanner used to process this {@code @ComponentScan} annotation should
	 * use its inherited bean name generator, e.g. the default
	 * {@link AnnotationBeanNameGenerator} or any custom instance supplied to the
	 * application context at bootstrap time.
	 * @see AnnotationConfigApplicationContext#setBeanNameGenerator(BeanNameGenerator)
	 * @see AnnotationBeanNameGenerator
	 * @see FullyQualifiedAnnotationBeanNameGenerator
	 */
	Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;
	/**
	 * The {@link ScopeMetadataResolver} to be used for resolving the scope of detected components.
	 */
	Class<? extends ScopeMetadataResolver> scopeResolver() default AnnotationScopeMetadataResolver.class;
		/**
	 * Indicates whether proxies should be generated for detected components, which may be
	 * necessary when using scopes in a proxy-style fashion.
	 * <p>The default is defer to the default behavior of the component scanner used to
	 * execute the actual scan.
	 * <p>Note that setting this attribute overrides any value set for {@link #scopeResolver}.
	 * @see ClassPathBeanDefinitionScanner#setScopedProxyMode(ScopedProxyMode)
	 */
	ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT;

    // 指定符合组件检测条件的类文件, 默认是包扫描下的"**/*.class"
	String resourcePattern() default ClassPathScanningCandidateComponentProvider.DEFAULT_RESOURCE_PATTERN;
    // 是否开启对标注了@Component, @Repository, @Service, @Controller注解的类进行检测。
	boolean useDefaultFilters() default true;
	// 包含的过滤条件
	Filter[] includeFilters() default {};
	// 排除的过滤条件
	Filter[] excludeFilters() default {};

	/**
	 * Specify whether scanned beans should be registered for lazy initialization.
	 * <p>Default is {@code false}; switch this to {@code true} when desired.
	 * @since 4.1
	 */
	boolean lazyInit() default false;
	/**
	 * Declares the type filter to be used as an {@linkplain ComponentScan#includeFilters
	 * include filter} or {@linkplain ComponentScan#excludeFilters exclude filter}.
	 */
	@Retention(RetentionPolicy.RUNTIME)
	@Target({})
	@interface Filter {
		/**
		 * The type of filter to use.
		 * <p>Default is {@link FilterType#ANNOTATION}.
		 * @see #classes
		 * @see #pattern
		 */
		FilterType type() default FilterType.ANNOTATION;

		/**
		 * Alias for {@link #classes}.
		 * @see #classes
		 */
		@AliasFor("classes")
		Class<?>[] value() default {};

		/**
		 * The class or classes to use as the filter.
		 * <p>The following table explains how the classes will be interpreted
		 * based on the configured value of the {@link #type} attribute.
		 * <table border="1">
		 * <tr><th>{@code FilterType}</th><th>Class Interpreted As</th></tr>
		 * <tr><td>{@link FilterType#ANNOTATION ANNOTATION}</td>
		 * <td>the annotation itself</td></tr>
		 * <tr><td>{@link FilterType#ASSIGNABLE_TYPE ASSIGNABLE_TYPE}</td>
		 * <td>the type that detected components should be assignable to</td></tr>
		 * <tr><td>{@link FilterType#CUSTOM CUSTOM}</td>
		 * <td>an implementation of {@link TypeFilter}</td></tr>
		 * </table>
		 * <p>When multiple classes are specified, <em>OR</em> logic is applied
		 * &mdash; for example, "include types annotated with {@code @Foo} OR {@code @Bar}".
		 * <p>Custom {@link TypeFilter TypeFilters} may optionally implement any of the
		 * following {@link org.springframework.beans.factory.Aware Aware} interfaces, and
		 * their respective methods will be called prior to {@link TypeFilter#match match}:
		 * <ul>
		 * <li>{@link org.springframework.context.EnvironmentAware EnvironmentAware}</li>
		 * <li>{@link org.springframework.beans.factory.BeanFactoryAware BeanFactoryAware}
		 * <li>{@link org.springframework.beans.factory.BeanClassLoaderAware BeanClassLoaderAware}
		 * <li>{@link org.springframework.context.ResourceLoaderAware ResourceLoaderAware}
		 * </ul>
		 * <p>Specifying zero classes is permitted but will have no effect on component
		 * scanning.
		 * @since 4.2
		 * @see #value
		 * @see #type
		 */
		@AliasFor("value")
		Class<?>[] classes() default {};

		/**
		 * The pattern (or patterns) to use for the filter, as an alternative
		 * to specifying a Class {@link #value}.
		 * <p>If {@link #type} is set to {@link FilterType#ASPECTJ ASPECTJ},
		 * this is an AspectJ type pattern expression. If {@link #type} is
		 * set to {@link FilterType#REGEX REGEX}, this is a regex pattern
		 * for the fully-qualified class names to match.
		 * @see #type
		 * @see #classes
		 */
		String[] pattern() default {};
	}
}

@ComponentScan扫描策略

(1)通过使用 value,basePackages 属性来指定扫描范围;
(2)自动扫描指定路径下带有 @Controller,@Service,@Repository,@Component 等注解标注的类到Spring容器中;
(3)通过 includeFilters 将扫描路径下没有以上注解的类加入 Spring 容器;
(4)通过 excludeFilters 将扫描路径下的类过滤并标识出无需加入到Spring 容器的类;
(5)通过自定义的方式,将符合规则的类加入到Spring容器中。

如何使用?

在基于SpringBoot框架的项目中,在默认的启动类上会被添加@SpringBootApplication注解,这个注解默认可以帮我们启用 SpringBoot 的自动配置功能。
@SpringBootApplication是一个组合注解,相当于使用一个@SpringBootApplication可以替代@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan几个注解联合使用。我们可以通过对@SpringBootApplication的属性scanBasePackages,实现对@ComponentScan中的属性basePackages进行自定义。

源码、示例及DEMO

源码、示例及DEMO

Spring Boot 中的 `@ComponentScan`:作用、原理与是否必须存在? 本文深入解析了Spring Boot中的@ComponentScan注解: 作用:该注解用于指定Spring容器扫描哪些包下的组件(如@Component、@Service等),将其注册为Bean。 默认行为:未显式声明时,Spring Boot会自动扫描启动类所在包及其子包下的所有组件。 使用场景: 需要扫描非启动类包下的组件(如common包) 多模块项目中统一管理扫描范围 注意事项: 显式声明会覆盖默认扫描范围 @SpringBootApplication已包含默认的@ComponentScan 推荐 阅读详情

相关推荐

【ESP32-IDF】I2S音频协议实战:从PDM麦克风到PCM扬声器的全链路解析

本文深入解析ESP32-S3的I2S音频协议,从PDM麦克风采集到PCM扬声器输出的全链路实现。详细介绍了硬件PDM转PCM、Standard模式配置及混合模式协同工作,提供实战代码与性能优化建议,助力开发者高效完成嵌入式音频项目开发。

pea55的博客 893

spring boot自动装配之@ComponentScan详解

1.@ComponentScan注解作用 @ComponentScan用于类或接口上主要是指定扫描路径,spring会把指定路径下带有指定注解的类自动装配到bean容器里。会被自动装配的注解包括@Controller、@Service、@Component、@Repository等等。与ComponentScan注解相对应的XML配置就是<context:component-scan/>, 根据指定的配置自动扫描package,将符合条件的组件加入到IOC容器中; XML的配置方式如下: &l

qq_39093474的博客 1万+

ApolloScape 数据集:YOLOv10 + UI界面实现与应用

是由百度Apollo团队发布的一个大规模自动驾驶数据集,涵盖了车辆、行人、骑行者等多种交通元素,旨在为自动驾驶技术的发展提供丰富的数据支持。数据集包含多种复杂的场景,例如城市道路、交叉口、车辆聚集等,能够帮助研究人员和开发者在多种现实环境下测试和验证目标检测模型。YOLO(You Only Look Once)系列算法是目前最流行的目标检测算法之一,因其高效、准确以及实时性强的特点被广泛应用于计算机视觉领域。YOLOv10是YOLO系列中的最新版本,在性能和效率上进行了多方面的优化。速度快。

YOLO 942

@ComponentScan 详解

@ComponentScan 的作用就是根据定义的扫描路径,把符合扫描规则的类装配到spring容器中,注解定义如下。 @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Documented @Repeatable(ComponentScans.class) public @interface ComponentScan { @AliasFor("basePackages") String[] value

dxyzhbb的博客 7万+

RT-Thread Studio 使用笔记(七)| 配合STM32CubeMX添加裸机驱动(以ADC为例)

1. 配置STM32CubeMX 2. 复制stm32xxxx_hal_msp.c文件 将 CubeMx 生成的代码 stm32f7xx_hal_msp.c 函数复制到 RT-Thread Studio 生成的工程中,并参与工程编译: 由于我们并没有使用 CubeMx 生成的工程,所以这里需要将 stm32f7xx_hal_msp.c 文件中 #include “main.h” 替换为 #i...

Mculover666的博客(嵌入式) 9636

基于Simulink的智能车辆电子稳定控制(ESC)仿真

本文完成了基于 Simulink 的智能车辆电子稳定控制(ESC),实现了:✅ 构建含轮胎非线性的车辆动力学模型✅ 设计滑模横摆稳定性控制器✅ 实现四轮制动力分配逻辑✅ 验证在双移线低附着场景下的卓越稳定性✅ 为主动安全控制系统开发提供完整范式。

xiaoheshang_123的博客 85

【Springboot】@ComponentScan 详解

这使得你可以将特定类型或其子类或实现类的组件自动注册到 Spring 容器中,从而实现更灵活的组件管理和配置。通过使用自定义过滤器,你可以根据更复杂的条件和逻辑来决定哪些组件会被扫描和注册到 Spring 容器中。注解时,你可以自定义过滤器来进一步控制哪些组件会被扫描和注册到 Spring 容器中。注解可以告诉 Spring 在指定的包或类路径下进行组件扫描,然后自动将被扫描到的组件注册到 Spring 容器中。是 Spring 框架中的一个注解,用于自动扫描和注册容器中的组件。类就会被自动注册到容器中。

怀着一颗学徒的心 8578

半导体晶圆调平系统:基于最小二乘法的实现方案

基于最小二乘法的晶圆调平技术通过数学建模与工程实现的结合,解决了半导体量测中高精度平面对准的核心问题。实际应用中,需根据设备特性优化采样策略、校准传感器误差,并通过实时性优化满足高产能场景需求。该方案的模块化设计(如分离数据采集、拟合计算、补偿输出)也为后续功能扩展(如引入机器学习优化拟合模型)提供了灵活性。

品质生活,极致编程。 1187

Spring Boot 中的 @ComponentScan 注解是什么,原理,如何使用

在本文中,我们介绍了 Spring Boot 中的 @ComponentScan 注解。这个注解可以让 Spring 自动扫描指定的包及其子包中的组件,并将它们自动装配到 Spring 容器中。我们还介绍了 @ComponentScan 注解的原理以及如何在 Spring Boot 中使用它。如果你正在开发一个大型的 Spring Boot 应用,那么使用 @ComponentScan 注解可以帮助你更加方便地管理和装配组件,减少手动配置的工作量。

徐师兄的博客 3101

Linux驱动学习--HCI框架及源码分析

目录 一、引言 二、HCI框架 三、pcm_read简要分析 一、引言 最近一直在分析蓝牙驱动,发现在底层驱动与上层协议栈间还有一层HCI,主机控制层,两者之间通过HCI协议通讯 而Linux也将HCI协议抽象层了一个框架。 为上层提供一个统一的接口,让上层协议不依赖于具体硬件的实现。HCI在硬件中的固件与HCI在主机端的驱动通信方式有多种,比如像 UART、USB和PC Card等等。hci_core.c相当于一个框架,用于把各种具体通信方式绞合起来,并提供一些公共函数的实现。 今天就来简单的分析一下 二

文艺小少年的博客 2008

SAP_ABAP_SD_BAPI清单案例教程——销售订单开票_BAPI_BILLINGDOC_CREATEMULTIPLE_VF01_S4版本

SAP BAPI(Business Application Programming Interface)是SAP系统中的一组规范和标准,用于从SAP系统中获取数据、输入数据和更新数据。这些API允许开发者以编程方式与SAP系统交互,而无需编写大量的自定义代码。2.1 Copy代码 直接可使用。2.2 VF01开票。

java_zhong1990的专栏 2217

【SpringBoot注解之@ComponentScan】

1.在SpringBoot中,启动类默认扫描所在包下的所有类,如果要扫描的类和启动类不再同一个包里,则不会扫描到,此时需要在启动类上使用@ComponentScan去指定扫描位置。useDefaultFilters: 配置是否开启可以对加@Component,@Repository,@Service,@Controller注解的类进行检测。5.默认将@Controller,@Service,@Repository,@Component注解的类装配到spring容器中。2.指定要扫描的类;

weixin_57895075的博客 719

手把手教你完成基于matlab的路面裂缝检测系统设计

裂缝是路面病害最早的形态之一,只有在裂缝出现的早期进行维护,才能有效地提高公路的使用寿命。因此,路面裂缝的检测识别系统对于提升公路质量有着重大的意义。首先,对路面裂缝图像进行相应的预处理,目的是减小环境因素的影响,消除无用的噪点。然后提取目标图像特征,判断路面裂缝类型,标记出路面裂缝的位置。最后通过设计的 GUI 界面来集成各个关键步骤,显示所得到的试验结果。仿真结果表明,设计的路面裂缝检测识别系统是高效可行的。

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

SpringBoot —— @ComponentScan注解

文章目录一、作用二、注解属性说明三、使用方式 一、作用 主要是从定义的扫描路径中,找出标识了需要装配的类自动装配到Spring的bean容器中。 简单的说就是 @ComponentScan告诉Spring从哪里找到bean,一旦指定了,Spring就会将指定的包及其下级的包中寻找bean。 在SpringBoot项目中,我们并没有显示的看到该注解,但是仍然能扫描到bean呢? 其实,在创建SpringBoot项目中,默认在启动类上添加了@SpringBootApplication注解,该注解中包含@Com

Davis 1915

IDEA的使用指南

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

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

Springboot注解@ServletComponentScan和@ComponentScan

一、SpringBoot中使用Servlet 在SpringBootApplication上使用@ServletComponentScan注解后,Servlet、Filter、Listener可以直接通过@WebServlet、@WebFilter、@WebListener注解自动注册,无需其他代码。 1.在入口Application类上加入注解@ServletComponentScan pack...

小强签名设计 的博客 10万+

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Spring Boot,注解,@ComponentScan

@ComponentScan 是 Spring 框架的核心注解,用于自动扫描并注册带有特定注解(如 @Component、@Service 等)的组件为 Spring Bean。默认扫描配置类所在包及其子包,可通过 basePackages 或 basePackageClasses 指定扫描范围。支持自定义过滤规则(includeFilters/excludeFilters)和类型安全的包指定方式。在 Spring Boot 中通常由 @SpringBootApplication 包含。合理配置扫描范围可优

Yqha1的博客 1088

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

SpringBoot @ComponentScan注解

1.@ComponentScan注解的作用 告诉spring从哪里装载bean到容器。 2.Springboot项目中如何使用@ComponentScan注解 如果你的其他包都在使用了@SpringBootApplication注解的main app所在的包及其下级包,则你什么都不用做,SpringBoot会自动帮你把其他包都扫描了 如果你有一些bean所在的包,不在main app的包及...

ayoungyeah的博客 947

【Springboot 】使用@ComponentScan注解

(准备工作:新建个和memberController类一样的 IndexController类,具体看代码) https://github.com/SsRong/springboot2.0-ssrtest01 我们在上个章节中学习了如何用@EnableAutoConfiguration来扫包自动配置,并启动springboot项目。但是上节课也讲到了@EnableAutoConfigurati...

qq_41738687的博客 1583

Springboot注解与分析之:@ComponentScan注解

Springboot注解与分析之:@ComponentScan注解) 使用Spring框架开发Java Web项目的读者一定都用过@Controller、@Service、@Repository等注解。查看源码会发现,这些注解上都会标注一个共同的注解@Component。 而在Spring IOC容器中@Controller、@Service、@Repository、@Component等注解的默认装配标识是@ComponentScan注解。 <!-- 自动扫描 --> <context:

zhengzaifeidelushang的博客 341

springboot @ComponentScan注解

在springboot当中,使用@SpringBootApplication注解,默认扫描启动类所在路径下的包文件,如果想要扫描其他包怎么办? springboot提供的@ComponentScan注解类,可以完成该项任务,点击进去,可以看到该注解,有两个互为别名的属性,value和basePackages ,使用方法分别是: @ComponentScan(value=“com.lixl.demo.application”)此时扫描范围是一个指定包范围 @ComponentScan(basePackages

weixin_38879931的博客 1153

Spring Boot的@SpringBootApplication、@EnableAutoConfiguration、@ComponentScan注解

Spring Boot的@SpringBootApplication、@EnableAutoConfiguration、@ComponentScan注解,我经常在启动类上傻傻分不清,@EnableAutoConfiguration这个注解是是Springboot根据我们所引入的jar包自动配置的,假设我们有自己的配置类则会覆盖@ComponentScan是告诉springboot进行包扫描的而@Sp

小小码农 1万+

SpringBoot中的 @ComponentScan 注解

SpringBoot 的 @ComponentScan 注解和 @Component 注解的区别

m0_50888347的博客 800

SpringBoot 注解@Slf4j @ComponentScan @Signature等

1.@Slf4j相当于private final Logger logger = LoggerFactory.getLogger(当前类名.class); @Sl4j注解,然后使用log打印日志; 2.@ComponentScan用于类或接口上主要是指定扫描路径,spring会把指定路径下带有指定注解的类自动装配到bean容器里。 会被自动装配的注解包括@Controller、@Service、@Component、@Repository等等. 3.@Transactional(rollbackFo...

wwwkm123的博客 1459

Springboot中@ComponentScan 注解

三个点: 1、工程中Application类的位置。默认情况下就不需要配置@ComponentScan这个注解了。 因为Application类,在启动的时候,默认是加载和Application类所在同一个目录下的所有类,包括所有子目录下的类。所以一般情况下,启动类的位置是 有特殊要求的。 如上图所示,Application.java 类在com.pa.market包下,所以它自动扫描同级目录market下的所有类。 2、假设写的模块,编译成了jar包,并且上传到了私服。在pom中以第三方包的形式依赖.

qq_43842093的博客 1105
上一篇: SpringBoot - @Autowired注解使用详解
下一篇: SpringBoot - @Component注解使用详解
cloneme01
博客等级 码龄20年 2万+粉丝 248原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cloneme01

谢谢您的支持与鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址