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
##注册ConfigurationClassPostProcessor.class的BeanDefinition
##解析启动配置类
##看到ConfigurationClassParser解析ComponentScans.class, ComponentScan.class注解
##ComponentScanAnnotationParser的parse方法解析
##包名为空,添加启动类所在的包
##找到启动类所在包,及子包所有的bean候选者
##至此类被扫描成BeanDefinition并注册到DefaultListableBeanFactory的beanDefinitionMap
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!