原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/14902155.html

 

原理

@SpringBootApplication 是一个复合注解,包括

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan

@SpringBootApplication 之 @ComponentScan

Note:

@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
  • excludeFilters:Specifies which types are not eligible for component scanning
  • @Filter:Filter annotation
  • FilterType.CUSTOM:Filter candidates using a given custom implementation
  • classes:Filter specific class, include TypeExcludeFilter, AutoConfigurationExcludeFilter

 

@ComponentScan 源码

@SpringBootApplication 之 @ComponentScan

Note:

  • 通常自定义一个Spring Bean,一般在类上加上注解 @Component、@Service、@Controller,定义好后,需要使用@ComponentScan 来告诉Spring IoC 容器去哪里装载自定义的Spring Bean
  • @SpringBootApplication 包含了@ComponentScan,所以@SpringBootApplication注解所在包及其子包目录下的Spring Bean都会被扫描并装载到Spring IoC容器。
  • 如果自定义的一个Spring Bean,不在@SpringBootApplication 注解所在包及其子包目录下,需要手动加上@ComponentScan 注解并指定自定义Spring Bean所在的包。

 

示例

Project Directory

@SpringBootApplication 之 @ComponentScan

 

Maven Dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>org.fool</groupId>
    <artifactId>hellospring</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-13
  • 2022-01-10
  • 2021-07-01
  • 2021-07-11
  • 2022-12-23
猜你喜欢
  • 2022-01-01
  • 2021-04-07
  • 2022-01-15
  • 2021-07-16
  • 2021-06-19
  • 2021-06-27
  • 2022-03-10
相关资源
相似解决方案