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 推荐 阅读详情

相关推荐

多目标跟踪(MOT)中的卡尔曼滤波(Kalman filter)和匈牙利(Hungarian)算法详解

多目标跟踪(MOT)中的卡尔曼滤波(Kalman filter)和匈牙利(Hungarian)算法详解 1. 概览 在开始具体讨论卡尔曼滤波和匈牙利算法之前,首先我们来看一下基于检测的目标跟踪算法的大致流程。 2. 卡尔曼滤波(Kalman filter) 目标跟踪中使用的就是最基础的 Kalman filter 算法。这里也仅仅讨论最基础的 Kalman filter 算法。 卡尔曼滤波算法的过程很简单,如下图所示。最核心的两个步骤就是预测和更新(下图的 correct)。 在目标跟踪任务中,目标的

生命在于折腾! 2万+

spring boot自动装配之@ComponentScan详解

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

qq_39093474的博客 1万+

Xshell 连接 kali 虚拟机教程

启动ssh服务,启动后重新查看ssh服务状态,如下图active(running)正常。至此便可以直接使用Xshell登录kali系统了。至此虚拟机已经可以上网。-查看ssh服务状态。

qq_40726937的博客 2219

@ComponentScan 详解

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

dxyzhbb的博客 7万+

秦时明月6.2魔改版_从零到一部署指南_含安卓客户端配置与GM后台直通

本文详细介绍了秦时明月6.2魔改版的从零到一部署指南,包括环境准备、服务端安装、安卓客户端配置以及GM后台直通等关键步骤。特别针对安卓客户端配置和GM工具使用提供了实用技巧,帮助用户快速搭建并优化游戏服务器,确保稳定运行。

weixin_42522964的博客 317

绿联NAS使用docker部署immich【pro系统】

随后去绿联你想要存放immich的地方创建一个文件夹,便于区分,如图,我创建了一个immich的文件夹。1.进入文件夹后面是有斜杠的(tips:只需要敲击前面几个字母,按tab键自动补全)cd:进入路径,1.可以是当前的下一层相对路径 2.也可以是完整的全路径。前言:好像没有绿联的教程,刚好自己也有需求,就顺便记录了。如果你的挂载实战情况比较复杂,接下来是喂到胃里的知识点。】下载文件(群晖的,别慌,能用),两份,红框的就是。首先,没什么好说的,去immich官网【点击1.终端,2.新增,3.确定。

weixin_45343644的博客 1781

【Springboot】@ComponentScan 详解

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

怀着一颗学徒的心 8576

【2026-Spark实验一-Windows中安装Spark环境】

本文详细介绍了在Windows系统中配置Spark 3.5.8开发环境的完整流程。主要内容包括:安装JDK 8并配置环境变量,下载并解压Spark 3.5.8预编译版,设置SPARK_HOME系统变量,配置Hadoop的winutils工具解决Windows兼容性问题。通过spark-shell和SparkPi示例程序验证环境配置成功,确保Spark能够正常运行分布式计算任务。文中特别强调了路径命名规范、环境变量设置顺序等关键细节,提供了完整的配置截图和验证方法,帮助开发者快速搭建稳定的Spark学习环境。

pblh123的专栏 1588

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

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

徐师兄的博客 3101

第 10 篇:深度学习的“军火库”——CNN、RNN与Transformer,AI如何看懂世界?

深度学习的革命,不是依赖单一的通用大脑,而是为不同任务打造了专属“军火库”:CNN用“局部感知”看懂图像,RNN用“循环记忆”理解序列,而Transformer则用“全局注意力”开启了AIGC时代。理解这些架构,不是记忆孤立的技术,而是洞察AI从“专才”走向“通才”的进化脉络。

maqh_csdn的博客 786

PCL 循环体素滤波

本文提出了一种自动循环体素滤波算法,用于解决点云配准中分辨率差异大、参数设置复杂的问题。算法通过计算点云分辨率(公式1),采用迭代方式调整体素尺寸(公式2),逐步逼近目标分辨率。该方法在保留几何特征的同时有效精简数据量,实现了均匀分辨率的自动调整。实验通过PCL库实现,展示了原始点云与滤波结果的对比效果,验证了算法在减少数据规模方面的有效性。该方法为点云配准提供了预处理解决方案,相关成果已发表于SCI期刊。

点云侠的博客 283

【SpringBoot注解之@ComponentScan】

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

weixin_57895075的博客 719

【AHE数据集】历史/未来全球网格热排放数据 PF-AHF

AHE数据集

WW、forever的博客 128

SpringBoot —— @ComponentScan注解

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

Davis 1913

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

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

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

Springboot注解@ServletComponentScan和@ComponentScan

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

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

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

Spring Boot,注解,@ComponentScan

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

Yqha1的博客 1081

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

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的博客 340

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的博客 1104
上一篇: 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、付费专栏及课程。

余额充值