@ComponentScan-自动扫描组件介绍


https://blog.csdn.net/H176Nhx7/article/details/120029675

一、@ComponentScan注解是什么

如果你理解了ComponentScan,你就理解了Spring是一个依赖注入(dependency injection)框架。所有的内容都是关于bean的定义及其依赖关系。
定义Spring Beans的第一步是使用正确的注解@Component或@Service或@Repository或者@Controller
但是,Spring不知道你定义了某个bean除非它知道从哪里可以找到这个bean
ComponentScan做的事情就是告诉Spring从哪里找到bean
由你来定义哪些包需要被扫描。一旦你指定了,Spring将会在被指定的包及其下级包中寻找bean
下面分别介绍在Spring Boot项目和非Spring Boot项目(如简单的JSP/Servlet或者Spring MVC应用)中如何定义@Component Scan

二、@ComponentScan注解的基本使用

1.Spring Boot项目

总结:

  • 如果你的其他包都在使用了@SpringBootApplication注解的main
    app所在的包及其下级包中,则你什么都不用做,SpringBoot会自动帮你把其他包都扫描了
  • 如果你有一些bean所在的包,不在main
    app的包及其下级包中,那么你需要手动加上@ComponentScan注解并指定那个bean所在的包

举个例子,看下面定义的类

@ComponentScan(“com.demo”)
@SpringBootApplication
public class SpringbootApplication {

方案2
定义分别扫描两个包
@ComponentScan({“com.demo.springboot”,”com.demo.somethingelse”})

@ComponentScan({"com.demo.package1","com.demo.package2"})
@Configuration
public class SpringConfiguration {

XML文件方式

            FilterType.ANNOTATION:按照注解

            FilterType.ASSIGNABLE_TYPE:按照给定的类型;

            FilterType.ASPECTJ:使用ASPECTJ表达式

            FilterType.REGEX:使用正则指定

            FilterType.CUSTOM:使用自定义规则)

            classes指定过滤的类
1.基本示例:

创建controller:

@Service
public class UserService {
}

创建dao:

@Configuration
@ComponentScan(value = "com.spring.annotation")
public class ScanConfig {
 
}

测试:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory

scanConfig
annotationConfig
userController
userDao
userService

可以看到对应的实体类已经注入到容器中

2.过滤指定的注解进行注入
  • excludeFilters (排除过滤器)
scanConfig
annotationConfig
userDao
userService

可以看到 原来的 userController 已经消失,说明没有被注入到容器中去

  • includeFilters (包含过滤器)
scanConfig
userController

可以看到只有 被@controller注解的bean注入到容器中去。useDefaultFilters默认的过滤规则是开启的,如果我们要自定义的话是要关闭的

       Java_spring