spring boot 自动扫描Controller、Service、Component原理

文章解释了在SpringBoot中,启动类使用@SpringApplication注解会自动扫描Controller、Service等带有@Component注解的组件,即使没有显式指定@ComponentScan。它详细阐述了扫描过程和注解的作用原理。
摘要由CSDN通过智能技术生成

项目里面为什么不加上@ComponentScan("com.yym.*")注解,也能加载到子目录里面的Controller,Service,Component的bean呢?

启动类没有@ComponentScan注解

@SpringBootApplication
public class BootStrap {
    public static void main(String[] args) {
        SpringApplication.run(BootStrap.class, args);
    }
}

原因:

spring boot 启动类加上@SpringBootApplication会自动扫描当前目录,及子目录下的Controller,Service,Component注解的bean。

查看@SpringBootApplication注解源码,里面有@ComponentScan注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication

查看Controller,Service注解源码都有Component注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";

}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";

}

原理:

##AnnotationConfigServletWebServerApplicationContext构造器初始化AnnotatedBeanDefinitionReader、ClassPathBeanDefinitionScanner

##AnnotatedBeanDefinitionReader构造器初始化调用AnnotationConfigUtils.registerAnnotationConfigProcessors静态方法注册ConfigurationClassPostProcessor.class

##注册ConfigurationClassPostProcessor.class的BeanDefinition

##解析启动配置类

##看到ConfigurationClassParser解析ComponentScans.class, ComponentScan.class注解

##ComponentScanAnnotationParser的parse方法解析

##包名为空,添加启动类所在的包

##找到启动类所在包,及子包所有的bean候选者

##至此类被扫描成BeanDefinition并注册到DefaultListableBeanFactory的beanDefinitionMap

  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值