- package demo.config;
- public class Red {
- }
-
- @EnableColor
- @Configuration
- public class ColorConfiguration {
- }
- @SpringBootApplication
- @MapperScan("demo.mapper")
- public class Springboot01Application {
-
- public static void main(String[] args) {
- AnnotationConfigApplicationContext ctx=new AnnotationConfigApplicationContext(ColorConfiguration.class);
- String[] beanDefinitionNames=ctx.getBeanDefinitionNames();
- Stream.of(beanDefinitionNames).forEach(System.out::println);
- }
-
- }
- @Configuration
- public class ColorRegistrarConfiguration {
-
- @Bean
- public Yellow yellow() {
- return new Yellow();
- }
- }
- @Documented
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.TYPE)
- @Import({Red.class,ColorRegistrarConfiguration.class})
- public @interface EnableColor {
- }
- @EnableColor
- @Configuration
- public class ColorConfiguration implements ImportSelector {
- @Override
- public String[] selectImports(AnnotationMetadata importingClassMetadata) {
- return new String[] {Blue.class.getName(), Green.class.getName()};
- }
- }
- public class ColorImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
-
- @Override
- public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
- registry.registerBeanDefinition("black", new RootBeanDefinition(Black.class));
- }
- }
SpringBoot自动配置完全由@enableAutoconfiguration开启
- @AutoConfigurationPackage
- @Import(AutoConfigurationImportSelector.class)
- public @interface EnableAutoConfiguration
@EnableAutoConfiguration是一个组合注解
- @Import(AutoConfigurationPackages.Registrar.class)
- public @interface AutoConfigurationPackage
主启动类必须放在所有自定义组件的包的最外层,以保证Spring能扫描到他们
实现原理:注解标注了@Improt,导入AutoCongurationPackages.Registrar
- static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
-
- @Override
- public void registerBeanDefinitions(AnnotationMetadata metadata,
- BeanDefinitionRegistry registry) {
- register(registry, new PackageImport(metadata).getPackageName());
- }
-
- @Override
- public Set
- return Collections.singleton(new PackageImport(metadata));
- }
-
- }
basePackage整合第三方技术
- public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar {
-
- private BeanFactory beanFactory;
-
- @Override
- public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
- if (!AutoConfigurationPackages.has(this.beanFactory)) {
- logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.");
- return;
- }
- logger.debug("Searching for mappers annotated with @Mapper");
-
- List
packages = AutoConfigurationPackages.get(this.beanFactory); - // logger ......
- // 注册Mapper ......
- }
扫描Mapper并注册到IOC容器的ImportBeandefinitionRegistrar,
扫描跟包 AutoConfigurationPackages.get(this.beanFactory)