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

项目里面为什么不加上@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

spring boot 自动扫描Controller、Service、Component原理_第1张图片

##注册ConfigurationClassPostProcessor.class的BeanDefinition

spring boot 自动扫描Controller、Service、Component原理_第2张图片

##解析启动配置类

spring boot 自动扫描Controller、Service、Component原理_第3张图片

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

spring boot 自动扫描Controller、Service、Component原理_第4张图片

##ComponentScanAnnotationParser的parse方法解析

spring boot 自动扫描Controller、Service、Component原理_第5张图片

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

spring boot 自动扫描Controller、Service、Component原理_第6张图片

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

spring boot 自动扫描Controller、Service、Component原理_第7张图片

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

spring boot 自动扫描Controller、Service、Component原理_第8张图片

你可能感兴趣的:(spring,boot,java,前端)