【Spring Boot 从零学习】10 SpringBoot源码讲解 - ComponentScan讲解

1.核心注解@ComponentScan
作用范围扫描的方式,扫描特定的注解,将其注册到Spring ioc容器中

@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)

excludeFilters:过滤不需要扫描的类型。 @Filter 过滤注解 FilterType.CUSTOM 过滤类型为自定义规则,即指定特定的class classes :过滤指定的class,即剔除了TypeExcludeFilter.class、AutoConfigurationExcludeFilter.class

从以上源码,我们可以得出结论:
1.@SpringBootApplication的源码包含了@ComponentScan, 故,只要@SpringBootApplication注解的所在的包及其下级包,都会讲class扫描到并装入spring ioc容器
2.如果你自定义的定义一个Spring bean,不在@SpringBootApplication注解的所在的包及其下级包, 都必须手动加上@ComponentScan注解并指定那个bean所在的包。

2.核心作用:
定义一个Spring bean 一般是在类上加上注解 @Service 或@Controller 或 @Component就可以, 但是,spring怎么知道有你这个bean的存在呢? 故,我们必须告诉spring去哪里找这个bean类。 @ComponentScan就是用来告诉spring去哪里找bean类。
告诉Spring去扫描@componentscan指定包下所有的注解类,然后将扫描到的类装入spring bean容器。 例如:@ComponentScan(“com.agan.boot.scan”),就只能扫描com.agan.boot.scan包下的注解类。 如果不写?就像@SpringBootApplication的@ComponentScan没有指定路径名?它去哪里找? @SpringBootApplication注解的所在的包及其下级包,都会讲class扫描到并装入spring ioc容器

3.实践
3.1 新建一个ComponentScan测试类

package com.agan.boot.scan;

import org.springframework.stereotype.Service;

@Service
public class TestComponentScan {
}
3.2在com.example.demo下面建个启动类
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(Application.class, args);
        TestComponentScan componentScan = run.getBean(TestComponentScan.class);
        System.out.println(componentScan.toString());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值