@Configuration 被注解的类将成为一个bean配置类。
@ComponentScan的作用就是自动扫描并加载符合条件的组件,比如@Component和@Repository等,最终将这些bean定义加载到spring容器中。
@EnableAutoConfiguration 借助@Import的支持,收集和注册依赖包中相关的bean定义。
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
@AutoConfigurationPackage:
使用@Import注解:@Import({Registrar.class})
Registrar 中
new AutoConfigurationPackages.PackageImport(metadata)).getPackageName()
new AutoConfigurationPackages.PackageImport(metadata)
这两句代码的作用就是加载启动类所在的包下的主类与子类的所有组件注册到spring容器,是springboot默认扫描启动类所在的包下的主类与子类的所有组件。
搜集并注册到spring容器的那些beans来自哪里?
@Import(AutoConfigurationImportSelector.class):
AutoConfigurationImportSelector:
AutoConfigurationImportSelector implements DeferredImportSelector;
DeferredImportSelector extends ImportSelector;
ImportSelector 中的 selectImports方法返回一组bean
如果要让一个普通类交给Spring容器管理,通常有以下方法:
1、使用 @Configuration与@Bean 注解
2、使用@Controller @Service @Repository @Component 注解标注该类,然后启用@ComponentScan自动扫描
3、使用@Import 方法