spring笔记-DeferredImportSelector

1.概念

有2个特点

  1. 继承该接口的ImportSelector会在最后执行
  2. 如果定义了1一个以上的DeferredImportSelector则使用Order接口来进行排序
/**
 * A variation of {@link ImportSelector} that runs after all {@code @Configuration} beans
 * have been processed. This type of selector can be particularly useful when the selected
 * imports are {@code @Conditional}.
 *
 * 

Implementations can also extend the {@link org.springframework.core.Ordered} * interface or use the {@link org.springframework.core.annotation.Order} annotation to * indicate a precedence against other {@link DeferredImportSelector}s. * * @author Phillip Webb * @since 4.0 */ public interface DeferredImportSelector extends ImportSelector { }

2.测试代码

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Import({DeferredImportSelector1.class, DeferredImportSelector2.class, ImportSelector1.class, ImportSelector2.class})
    public static @interface Sample {
    }


    public static class ImportSelector1 implements ImportSelector {

        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            ImportSelectorTests.importFrom.put(getClass(), importingClassMetadata.getClassName());
            return new String[] { ImportedSelector1.class.getName() };
        }
    }


    public static class ImportSelector2 implements ImportSelector {

        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            ImportSelectorTests.importFrom.put(getClass(), importingClassMetadata.getClassName());
            return new String[] { ImportedSelector2.class.getName() };
        }
    }


    public static class DeferredImportSelector1 implements DeferredImportSelector, Ordered {

        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            ImportSelectorTests.importFrom.put(getClass(), importingClassMetadata.getClassName());
            return new String[] { DeferredImportedSelector1.class.getName() };
        }

        @Override
        public int getOrder() {
            return Ordered.LOWEST_PRECEDENCE;
        }
    }


    @Order(Ordered.HIGHEST_PRECEDENCE)
    public static class DeferredImportSelector2 implements DeferredImportSelector {

        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            ImportSelectorTests.importFrom.put(getClass(), importingClassMetadata.getClassName());
            return new String[] { DeferredImportedSelector2.class.getName() };
        }
    }

执行的先后顺序为
ImportSelector1-> ImportSelector2-> DeferredImportSelector2-> DeferredImportSelector1

参考:
https://www.jianshu.com/p/5f99d0809eaa

你可能感兴趣的:(spring笔记-DeferredImportSelector)