Spring boot @EnableAutoConfigura

2019-04-26  本文已影响0人  HelloWide
@SuppressWarnings("deprecation")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * @return the classes to exclude
     * 根据类型排除
     */
    Class<?>[] exclude() default {};

    /**
     * Exclude specific auto-configuration class names such that they will never be
     * applied.
     * @return the class names to exclude
     * @since 1.3.0
     * 根据名称排除
     */
    String[] excludeName() default {};

}

Then...

/**
 * {@link DeferredImportSelector} to handle {@link EnableAutoConfiguration
 * auto-configuration}. This class can also be subclassed if a custom variant of
 * {@link EnableAutoConfiguration @EnableAutoConfiguration}. is needed.
 *
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @author Stephane Nicoll
 * @author Madhura Bhave
 * @since 1.3.0
 * @see EnableAutoConfiguration
 */
public class AutoConfigurationImportSelector
        implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,
        BeanFactoryAware, EnvironmentAware, Ordered {
    ...
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        //判断是否启用自动配置,默认true,可覆盖isEnable自定义实现
        if (!isEnabled(annotationMetadata)) {
            return NO_IMPORTS;
        }
        try {
            AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
                    .loadMetadata(this.beanClassLoader);
            AnnotationAttributes attributes = getAttributes(annotationMetadata);
            //获取类路径下META-INF/spring.factories下key为EnableAutoConfiguration全限定名对应值
            List<String> configurations = getCandidateConfigurations(annotationMetadata,
                    attributes);
            //去重
            configurations = removeDuplicates(configurations);
            //根据order优先级排序
            configurations = sort(configurations, autoConfigurationMetadata);
            //排除部分类:1.根据class来排除(exclude),2.根据class name(excludeName)来排除
            Set<String> exclusions = getExclusions(annotationMetadata, attributes);
            checkExcludedClasses(configurations, exclusions);
            configurations.removeAll(exclusions);
            //载的类中不是所有都是要加载的,spring boot 提供了很多条件注解
            configurations = filter(configurations, autoConfigurationMetadata);
            //导入自动配置类时触发的事件处理,广播事件
            fireAutoConfigurationImportEvents(configurations, exclusions);
            return configurations.toArray(new String[configurations.size()]);
        }
        catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }

    ...

}

上一篇下一篇

猜你喜欢

热点阅读