- pom.xml中导入的第三方jar包依赖是如何实现自动注入bean容器的?
另一篇文章中提到入口类的@SpringBootApplication
注解整合了@EnableAutoConfiguration
注解。
@EnableAutoConfiguration
注解源码如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
@EnableAutoConfiguration
注解通过@Import
导入的处理类是AutoConfigurationImportSelector,AutoConfigurationImportSelector源码如下:
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware,
ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
private static final AutoConfigurationEntry EMPTY_ENTRY = new AutoConfigurationEntry();
private static final String[] NO_IMPORTS = {};
private static final Log logger = LogFactory.getLog(AutoConfigurationImportSelector.class);
private static final String PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
private ConfigurableListableBeanFactory beanFactory;
private Environment environment;
private ClassLoader beanClassLoader;
private ResourceLoader resourceLoader;
private ConfigurationClassFilter configurationClassFilter;
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
通过selectImports()方法追踪getAutoConfigurationEntry(),源码如下:
configurations作为AutoConfigurationEntry的构造参数返回,追踪对configurations的赋值getCandidateConfigurations()方法,源码如下:
通过SpringFactoriesLoader获得configurations并返回,追踪SpringFactoriesLoader源码:
扫描所有jar包类路径下 META‐INF下的spring.factories文件,将EnableAutoConfiguration的值加入到bean容器中,每一个XxxAutoConfiguration类都是一个组件,就实现了自动配置。
例如对于MyBatis的整合,就是通过spring.factories文件中EnableAutoConfiguration的值MyBatisAutoConfiguration导入MyBatis的配置。