在 SpringApplication#refresh
方法中,會去調(diào)用BeanDefinitionPostProcessor
去進(jìn)行預(yù)處理动漾,這里有一個很重要的 processor
就是 ConfigurationClassPostProcessor
, 他主要負(fù)責(zé)將 config bean 加載到 beaDefinitionMap 中蘸秘。
postProcessBeanDefinitionRegistry
我們先來看一下代碼:
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
}
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + registry);
}
this.registriesPostProcessed.add(registryId);
processConfigBeanDefinitions(registry);
}
主要做了兩件事情:
1飞蚓、生成當(dāng)前 registry 的 id,然后到 registriesPostProcessed
和 registriesPostProcessed
中查找眯勾,是否存在吨拍,主要作用是去重褪猛。
2、假如沒有重復(fù)調(diào)用 processConfigBeanDefinitions
去加載羹饰。
processConfigBeanDefinitions
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
// 獲取已經(jīng)注冊的 bean 名稱伊滋,這里一般是我們的啟動 Application 類。
String[] candidateNames = registry.getBeanDefinitionNames();
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
// 假如 beanDefinition 中的 ConfigurationClass 屬性為 full 或者 lite 那代表已經(jīng)解析過了队秩,跳過笑旺。
if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
// 判斷當(dāng)前類是否是 config 類,假如是就加入到 configCandidates 中馍资。
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
// 假如 configCandidates 為空就返回
// Return immediately if no @Configuration classes were found
if (configCandidates.isEmpty()) {
return;
}
// Sort by previously determined @Order value, if applicable
// 對 configCandidates 使用 @Order 注解進(jìn)行排序
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});
// Detect any custom bean name generation strategy supplied through the enclosing application context
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry) {
sbr = (SingletonBeanRegistry) registry;
if (!this.localBeanNameGeneratorSet) {
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
if (generator != null) {
// 設(shè)置 beanNameGenerator
this.componentScanBeanNameGenerator = generator;
this.importBeanNameGenerator = generator;
}
}
}
if (this.environment == null) {
this.environment = new StandardEnvironment();
}
// Parse each @Configuration class
//實例化 ConfigurationClassParser 為后續(xù)解析準(zhǔn)備筒主。
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
// 初始話 candidates 和 alreadyParsed 兩個集合
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
do {
// 進(jìn)行解析
parser.parse(candidates);
parser.validate();
// 獲取解析到的 ConfigurationClass
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
// Read the model and create bean definitions based on its content
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
// 加載 ConfigurationClass 的 beanDefinition
this.reader.loadBeanDefinitions(configClasses);
// 添加到 ConfigurationClass 中。
alreadyParsed.addAll(configClasses);
candidates.clear();
if (registry.getBeanDefinitionCount() > candidateNames.length) {
String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
}
}
主要做了如下7件事情:
1鸟蟹、獲取已經(jīng)注冊的bean名稱進(jìn)行遍歷:
2乌妙、對configCandidates 進(jìn)行 排序,按照@Order 配置的值進(jìn)行排序。
3建钥、如果BeanDefinitionRegistry 是SingletonBeanRegistry 子類的話,將registry強(qiáng)轉(zhuǎn)為SingletonBeanRegistry藤韵。
4、實例化ConfigurationClassParser 為了解析各個配置類.實例化2個set,candidates 用于將之前加入的configCandidates 進(jìn)行去重,alreadyParsed 用于判斷是否處理過熊经。
5泽艘、進(jìn)行解析。
6镐依、如果SingletonBeanRegistry 不包含org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry,則注冊一個,bean 為 ImportRegistry. 一般都會進(jìn)行注冊的匹涮。
7、清除緩存槐壳。
我們先來看一下判斷該 bean 是否為 configClass 的方法然低。
ConfigurationClassUtils#checkConfigurationClassCandidate
public static boolean checkConfigurationClassCandidate(
BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
// 獲取類名,假如不存在則返回。
String className = beanDef.getBeanClassName();
if (className == null || beanDef.getFactoryMethodName() != null) {
return false;
}
// 獲取 AnnotationMetadata
AnnotationMetadata metadata;
if (beanDef instanceof AnnotatedBeanDefinition &&
className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) {
// Can reuse the pre-parsed metadata from the given BeanDefinition...
// 檢查是否可以是 AnnotatedBeanDefinition 脚翘,是就直接從 BeanDefinition 中獲取
metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata();
}
else if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
// Check already loaded Class if present...
// since we possibly can't even load the class file for this Class.
// 如果BeanDefinition 是 AnnotatedBeanDefinition的實例,并且beanDef 有 beanClass 屬性存在沒有則實例化StandardAnnotationMetadata
Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass();
if (BeanFactoryPostProcessor.class.isAssignableFrom(beanClass) ||
BeanPostProcessor.class.isAssignableFrom(beanClass) ||
AopInfrastructureBean.class.isAssignableFrom(beanClass) ||
EventListenerFactory.class.isAssignableFrom(beanClass)) {
return false;
}
metadata = AnnotationMetadata.introspect(beanClass);
}
else {
try {
// 否則 通過MetadataReaderFactory 中的MetadataReader 進(jìn)行讀取
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
metadata = metadataReader.getAnnotationMetadata();
}
catch (IOException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not find class file for introspecting configuration annotations: " +
className, ex);
}
return false;
}
}
// 如果存在Configuration 注解,則為BeanDefinition 設(shè)置configurationClass屬性為full
Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
}
// 如果AnnotationMetadata 中有Component,ComponentScan,Import,ImportResource 注解中的任意一個,或者存在 被@bean 注解的方法,則返回true
else if (config != null || isConfigurationCandidate(metadata)) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
}
else {
return false;
}
// It's a full or lite configuration candidate... Let's determine the order value, if any.
Integer order = getOrder(metadata);
if (order != null) {
beanDef.setAttribute(ORDER_ATTRIBUTE, order);
}
return true;
}
詳細(xì)的內(nèi)容都行卸載注釋中了,其實主要是對該類的注解進(jìn)行判斷绍哎。
ConfigurationClassParser#parse
public void parse(Set<BeanDefinitionHolder> configCandidates) {
for (BeanDefinitionHolder holder : configCandidates) {
BeanDefinition bd = holder.getBeanDefinition();
try {
if (bd instanceof AnnotatedBeanDefinition) {
parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
}
else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
}
else {
parse(bd.getBeanClassName(), holder.getBeanName());
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
}
}
this.deferredImportSelectorHandler.process();
}
其主要做了兩件事情:
1来农、遍歷configCandidates ,進(jìn)行處理.根據(jù)BeanDefinition 的類型 做不同的處理,一般都會調(diào)用ConfigurationClassParser#parse 進(jìn)行解析。
2崇堰、處理ImportSelect沃于。
我們先來看一下第一步:
ConfigurationClassParser#parse
protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
return;
}
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
if (existingClass != null) {
if (configClass.isImported()) {
if (existingClass.isImported()) {
existingClass.mergeImportedBy(configClass);
}
// Otherwise ignore new imported config class; existing non-imported class overrides it.
return;
}
else {
// Explicit bean definition found, probably replacing an import.
// Let's remove the old one and go with the new one.
this.configurationClasses.remove(configClass);
this.knownSuperclasses.values().removeIf(configClass::equals);
}
}
// Recursively process the configuration class and its superclass hierarchy.
SourceClass sourceClass = asSourceClass(configClass, filter);
do {
sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
}
while (sourceClass != null);
this.configurationClasses.put(configClass, configClass);
}
主要做如下4件事情:
1、調(diào)用 shouldSkip 方法來判斷該 configClass 是否需要 跳過海诲。
2繁莹、處理Imported 的情況。
3特幔、遞歸調(diào)用進(jìn)行解析咨演。
4、添加到configurationClasses中蚯斯。
我們先來看一下 shouldSkip 方法:
public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
return false;
}
if (phase == null) {
if (metadata instanceof AnnotationMetadata &&
ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
}
return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
}
List<Condition> conditions = new ArrayList<>();
for (String[] conditionClasses : getConditionClasses(metadata)) {
for (String conditionClass : conditionClasses) {
Condition condition = getCondition(conditionClass, this.context.getClassLoader());
conditions.add(condition);
}
}
AnnotationAwareOrderComparator.sort(conditions);
for (Condition condition : conditions) {
ConfigurationPhase requiredPhase = null;
if (condition instanceof ConfigurationCondition) {
requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
}
if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
return true;
}
}
return false;
}
主要做4件事情:
1薄风、判斷該類是否被 Condition 注解修飾,假如沒有就直接返回拍嵌。
2遭赂、如果參數(shù)中沒有設(shè)置條件注解的生效階段
(1)、是配置類的話直接使用PARSE_CONFIGURATION階段,遞歸調(diào)用shouldSkip 進(jìn)行判斷横辆。
(2)撇他、否則使用REGISTER_BEAN階段,遞歸調(diào)用shouldSkip 進(jìn)行判斷。
3狈蚤、獲取配置類的條件注解得到條件數(shù)據(jù)困肩,并添加到集合中.
4、遍歷conditions,進(jìn)行判斷,如果階段不滿足條件的話脆侮,返回true并跳過這個bean的解析僻弹。
接下來我們看一下真正解析的步驟:
protected final SourceClass doProcessConfigurationClass(
ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
throws IOException {
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
// Recursively process any member (nested) classes first
processMemberClasses(configClass, sourceClass, filter);
}
// Process any @PropertySource annotations
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
processPropertySource(propertySource);
}
else {
logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}
}
// Process any @ComponentScan annotations
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
for (AnnotationAttributes componentScan : componentScans) {
// The config class is annotated with @ComponentScan -> perform the scan immediately
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
// Check the set of scanned definitions for any further config classes and parse recursively if needed
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
// Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
// Process any @ImportResource annotations
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
configClass.addImportedResource(resolvedResource, readerClass);
}
}
// Process individual @Bean methods
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
// Process default methods on interfaces
processInterfaces(configClass, sourceClass);
// Process superclass, if any
if (sourceClass.getMetadata().hasSuperClass()) {
String superclass = sourceClass.getMetadata().getSuperClassName();
if (superclass != null && !superclass.startsWith("java") &&
!this.knownSuperclasses.containsKey(superclass)) {
this.knownSuperclasses.put(superclass, configClass);
// Superclass found, return its annotation metadata and recurse
return sourceClass.getSuperClass();
}
}
// No superclass -> processing is complete
return null;
}
主要做了如下8件事情:
1、如果該類使用 @Component 注解他嚷,調(diào)用 processMemberClasses 方法蹋绽,其主要作用是將類放到 importStack 中,并且判斷是否有循環(huán)依賴度問題筋蓖。
2卸耘、處理@PropertySource.通過遍歷該類中的@PropertySource的注解,如果該類中的environment是ConfigurableEnvironment 子類的話,則調(diào)用processPropertySource進(jìn)行處理。
3粘咖、處理@ComponentScan,通過遍歷該類上的@ComponentScan 注解蚣抗,并使用 conditionEvaluator.shouldSkip 進(jìn)行判斷是否需要跳過。沒有就通過ComponentScanAnnotationParser#parse方法進(jìn)行掃描:
public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
BeanUtils.instantiateClass(generatorClass));
ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
scanner.setScopedProxyMode(scopedProxyMode);
}
else {
Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
}
scanner.setResourcePattern(componentScan.getString("resourcePattern"));
for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
for (TypeFilter typeFilter : typeFiltersFor(filter)) {
scanner.addIncludeFilter(typeFilter);
}
}
for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
for (TypeFilter typeFilter : typeFiltersFor(filter)) {
scanner.addExcludeFilter(typeFilter);
}
}
boolean lazyInit = componentScan.getBoolean("lazyInit");
if (lazyInit) {
scanner.getBeanDefinitionDefaults().setLazyInit(true);
}
Set<String> basePackages = new LinkedHashSet<>();
String[] basePackagesArray = componentScan.getStringArray("basePackages");
for (String pkg : basePackagesArray) {
String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
Collections.addAll(basePackages, tokenized);
}
for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
basePackages.add(ClassUtils.getPackageName(clazz));
}
if (basePackages.isEmpty()) {
basePackages.add(ClassUtils.getPackageName(declaringClass));
}
scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
@Override
protected boolean matchClassName(String className) {
return declaringClass.equals(className);
}
});
return scanner.doScan(StringUtils.toStringArray(basePackages));
}
1、初始化 ClassPathBeanDefinitionScanner翰铡。
2钝域、為 ClassPathBeanDefinitionScanner 設(shè)置 nameGenerator、scopedProxy锭魔、scopeResolver例证、includeFilters 和 excludeFilters
3、調(diào)用 scanner.doScan 方法迷捧,進(jìn)行掃描:
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
for (String basePackage : basePackages) {
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
for (BeanDefinition candidate : candidates) {
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}
1 织咧、遍歷basePackages,通過findCandidateComponents方法掃描basePackage路徑下的java文件。
2漠秋、假如存在笙蒙,就遍歷這路徑上的類:
(1)解析 scope屬性。
(2)生成 name 屬性
(3)檢查當(dāng)前bean是否已經(jīng)注冊,如果沒有注冊的話,則生成 BeanDefinitionHolder庆锦,并添加到 添加到beanDefinitions中
(4)向BeanDefinitionRegistry進(jìn)行注冊捅位。
4、處理@Import 注解
private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter,
boolean checkForCircularImports) {
// 假如 importCandidates 為空搂抒,就直接返回
if (importCandidates.isEmpty()) {
return;
}
// 檢查循環(huán)依賴問題绿渣,
if (checkForCircularImports && isChainedImportOnStack(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
}
else {
this.importStack.push(configClass);
try {
// 如果沒有循環(huán)依賴問題,就遍歷出路燕耿。
for (SourceClass candidate : importCandidates) {
if (candidate.isAssignable(ImportSelector.class)) {
// Candidate class is an ImportSelector -> delegate to it to determine imports
Class<?> candidateClass = candidate.loadClass();
ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
this.environment, this.resourceLoader, this.registry);
Predicate<String> selectorFilter = selector.getExclusionFilter();
if (selectorFilter != null) {
exclusionFilter = exclusionFilter.or(selectorFilter);
}
if (selector instanceof DeferredImportSelector) {
this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
}
else {
String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
}
}
else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
// Candidate class is an ImportBeanDefinitionRegistrar ->
// delegate to it to register additional bean definitions
Class<?> candidateClass = candidate.loadClass();
ImportBeanDefinitionRegistrar registrar =
ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
this.environment, this.resourceLoader, this.registry);
configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
}
else {
// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
// process it as an @Configuration class
this.importStack.registerImport(
currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter);
}
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to process import candidates for configuration class [" +
configClass.getMetadata().getClassName() + "]", ex);
}
finally {
this.importStack.pop();
}
}
}
主要處理流程如下:
1中符、判斷 importCandidates 是否為空,假如不是就返回誉帅。
2淀散、對其進(jìn)行循環(huán)依賴檢查。
3蚜锨、將其加入到 importstack 中档插,然后依次遍歷。
(1)如果是importSelect 子類亚再,就實例化 ImportSelector 對象郭膛,通過 ParserStrategyUtils#instantiateClass 方法。
[1]設(shè)置 ImportSelector exclusionFilter 屬性氛悬。
[2]假如 selector 是 DeferredImportSelector 屬性则剃,就調(diào)用 deferredImportSelectorHandler#handle 方法。
[3]假如不是最后調(diào)用 processImports 方法如捅。
(2) 如果該類是 ImportBeanDefinitionRegistrar的子類棍现,,則實例化后,調(diào)用ParserStrategyUtils#invokeAwareMethods,添加到configClass中。
(3)最后假如都不是就加入到importStack后調(diào)用processConfigurationClass 進(jìn)行處理镜遣。
5己肮、處理 @ImportResource 注解,先重 config 類中查找是否存在該注解,假如存在谎僻,就獲取其 location 屬性娄柳,然后遍歷 location 位置中的 bean,加入到 configClass 中的 ImportedResource艘绍。
6赤拒、處理 @Bean 的方法,遍歷 @Bean 的方法鞍盗,并放到 configClass 的 BeanMethod 中需了。
7跳昼、遍歷 configClass 的所有接口的 @Bean 的方法般甲,并放到 configClass 的 BeanMethod 中。
8鹅颊、如果存在父類的話敷存,就將父類放到 knownSuperclasses 中,并返回堪伍,返回就類似于遞歸調(diào)用锚烦。否則返回 null。
我們回到ConfigurationClassPostProcessor的processConfigBeanDefinitions方法中帝雇,接下來是調(diào)用 ConfigurationClassBeanDefinitionReader#loadBeanDefinitions 方法涮俄。
public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator();
for (ConfigurationClass configClass : configurationModel) {
loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);
}
}
如上,主要做兩件事情:
1尸闸、實例化 TrackedConditionEvaluator彻亲;
2、遍歷configurationModel 吮廉,使用loadBeanDefinitionsForConfigurationClass 方法加載 BeanDefinition苞尝。
loadBeanDefinitionsForConfigurationClass 方法如下:
private void loadBeanDefinitionsForConfigurationClass(
ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {
if (trackedConditionEvaluator.shouldSkip(configClass)) {
String beanName = configClass.getBeanName();
if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) {
this.registry.removeBeanDefinition(beanName);
}
this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName());
return;
}
if (configClass.isImported()) {
registerBeanDefinitionForImportedConfigurationClass(configClass);
}
for (BeanMethod beanMethod : configClass.getBeanMethods()) {
loadBeanDefinitionsForBeanMethod(beanMethod);
}
loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
}
主要做了如下幾件事情:
1、調(diào)用 trackedConditionEvaluator 來判斷條件注解宦芦,是否需要跳過這個 config 類宙址。如果需要,就將這個類從容器中移除调卑,并且從 importRegistry 中移除抡砂。
2、如果當(dāng)前類中存在@Import 注解恬涧,調(diào)用 registerBeanDefinitionForImportedConfigurationClass 方法進(jìn)行注冊:
private void registerBeanDefinitionForImportedConfigurationClass(ConfigurationClass configClass) {
AnnotationMetadata metadata = configClass.getMetadata();
AnnotatedGenericBeanDefinition configBeanDef = new AnnotatedGenericBeanDefinition(metadata);
ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(configBeanDef);
configBeanDef.setScope(scopeMetadata.getScopeName());
String configBeanName = this.importBeanNameGenerator.generateBeanName(configBeanDef, this.registry);
AnnotationConfigUtils.processCommonDefinitionAnnotations(configBeanDef, metadata);
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(configBeanDef, configBeanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
this.registry.registerBeanDefinition(definitionHolder.getBeanName(), definitionHolder.getBeanDefinition());
configClass.setBeanName(configBeanName);
if (logger.isTraceEnabled()) {
logger.trace("Registered bean definition for imported class '" + configBeanName + "'");
}
}
主要做的事情如下:
1舀患、根據(jù) configClass 的 AnnotatedGenericBeanDefinition 生成 BeanDefinition。
2气破、對BeanDefinition 進(jìn)行屬性設(shè)置:
1聊浅、解析 configClass的Scope。
2、生成 bean 的 id低匙。
3旷痕、設(shè)置 bean 的一些屬性,如 lazy 和 primary 等顽冶。
回到上面 loadBeanDefinitionsForConfigurationClass 方法欺抗。
3、遍歷BeanMethods,依次對其調(diào)用loadBeanDefinitionsForBeanMethod進(jìn)行注冊强重。
private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
// 獲取父的 configClass
ConfigurationClass configClass = beanMethod.getConfigurationClass();
// 獲取 beanMethod 的 MethodMetadata 和 methodName
MethodMetadata metadata = beanMethod.getMetadata();
String methodName = metadata.getMethodName();
// 判斷是否需要跳過绞呈,假如 conditionEvaluator#shouldSkip 返回 TRUE ,就將其放入 skippedBeanMethods 中并返回间景。
// Do we need to mark the bean as skipped by its condition?
if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
configClass.skippedBeanMethods.add(methodName);
return;
}
// 如果configClass的skippedBeanMethods包含該methodName的話,不進(jìn)行處理,
if (configClass.skippedBeanMethods.contains(methodName)) {
return;
}
// 從@Bean 注解中獲取 name 假如為空就將 methodName 作為 name
AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
Assert.state(bean != null, "No @Bean annotation attributes");
//
// Consider name and any aliases
List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name")));
String beanName = (!names.isEmpty() ? names.remove(0) : methodName);
// 為 bean 設(shè)置 alias
// Register aliases even when overridden
for (String alias : names) {
this.registry.registerAlias(beanName, alias);
}
// 查看是否存在重復(fù)注冊的場景
// Has this effectively been overridden before (e.g. via XML)?
if (isOverriddenByExistingDefinition(beanMethod, beanName)) {
if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) {
throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(),
beanName, "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName() +
"' clashes with bean name for containing configuration class; please make those names unique!");
}
return;
}
// 實例化 ConfigurationClassBeanDefinition
ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata, beanName);
beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));
// 如果是靜態(tài)方法佃声,則設(shè)置 setBeanClassName,
if (metadata.isStatic()) {
// static @Bean method
if (configClass.getMetadata() instanceof StandardAnnotationMetadata) {
beanDef.setBeanClass(((StandardAnnotationMetadata) configClass.getMetadata()).getIntrospectedClass());
}
else {
beanDef.setBeanClassName(configClass.getMetadata().getClassName());
}
beanDef.setUniqueFactoryMethodName(methodName);
}
else {
// instance @Bean method
// 如果是實例方法的話,則將configClass的BeanName設(shè)置為FactoryBeanName,methodName設(shè)置為UniqueFactoryMethodName
beanDef.setFactoryBeanName(configClass.getBeanName());
beanDef.setUniqueFactoryMethodName(methodName);
}
if (metadata instanceof StandardMethodMetadata) {
beanDef.setResolvedFactoryMethod(((StandardMethodMetadata) metadata).getIntrospectedMethod());
}
// 設(shè)置注入模式為構(gòu)造器注入模式
beanDef.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
// 設(shè)置skipRequiredCheck屬性為true beanDef.setAttribute(org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.
SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);
// 6.4 進(jìn)行一些常用的屬性設(shè)置
AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);
Autowire autowire = bean.getEnum("autowire");
if (autowire.isAutowire()) {
beanDef.setAutowireMode(autowire.value());
}
boolean autowireCandidate = bean.getBoolean("autowireCandidate");
if (!autowireCandidate) {
beanDef.setAutowireCandidate(false);
}
// 設(shè)置 initMethod
String initMethodName = bean.getString("initMethod");
if (StringUtils.hasText(initMethodName)) {
beanDef.setInitMethodName(initMethodName);
}
// 設(shè)置 destroyMethod
String destroyMethodName = bean.getString("destroyMethod");
beanDef.setDestroyMethodName(destroyMethodName);
// 設(shè)置ScopedProxyMode
// Consider scoping
ScopedProxyMode proxyMode = ScopedProxyMode.NO;
AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class);
if (attributes != null) {
beanDef.setScope(attributes.getString("value"));
proxyMode = attributes.getEnum("proxyMode");
if (proxyMode == ScopedProxyMode.DEFAULT) {
proxyMode = ScopedProxyMode.NO;
}
}
// 如果 ScopedProxyMode 為 NO 就生成代理
// Replace the original bean definition with the target one, if necessary
BeanDefinition beanDefToRegister = beanDef;
if (proxyMode != ScopedProxyMode.NO) {
BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(
new BeanDefinitionHolder(beanDef, beanName), this.registry,
proxyMode == ScopedProxyMode.TARGET_CLASS);
beanDefToRegister = new ConfigurationClassBeanDefinition(
(RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata, beanName);
}
if (logger.isTraceEnabled()) {
logger.trace(String.format("Registering bean definition for @Bean method %s.%s()",
configClass.getMetadata().getClassName(), beanName));
}
// 注冊
this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}
主要做了7件事情:
1倘要、獲取 configClass 圾亏、Methodname 和 MethodMetadata 。
2封拧、判斷是否需要跳過出來:
(1)志鹃、調(diào)用 conditionEvaluator#shouldSkip 方法是否需要跳過,需要返回泽西。
(2)曹铃、查看 skippedBeanMethods 中是否包含該方法,有則返回捧杉。
3陕见、從 @Bean 注解中獲取 name 假如為空就查找 methodName ,設(shè)置為 bean name糠溜。
4淳玩、對 name 的別名進(jìn)行注冊。
5非竿、 實例化 ConfigurationClassBeanDefinition 蜕着,如果該方法是靜態(tài)方法,設(shè)置該方法為工廠方法红柱,否則如果是實例方法的話,則將configClass的BeanName設(shè)置為FactoryBeanName,methodName設(shè)置為UniqueFactoryMethodName承匣,然后設(shè)置 initmethod 和 destroymethod ,最后設(shè)置 ScopedProxyMode 設(shè)置為 NO 并生成代理锤悄。
6韧骗、 注冊 Bean。
4零聚、處理 @ImportResource 注解袍暴,具體如下:
private void loadBeanDefinitionsFromImportedResources(
Map<String, Class<? extends BeanDefinitionReader>> importedResources) {
Map<Class<?>, BeanDefinitionReader> readerInstanceCache = new HashMap<>();
// 遍歷所有的 importedResources
importedResources.forEach((resource, readerClass) -> {
// Default reader selection necessary?
// 如果是 BeanDefinitionReader些侍,就查看是否是 groovy 類,假如不是就使用 XmlBeanDefinitionReader 類
if (BeanDefinitionReader.class == readerClass) {
if (StringUtils.endsWithIgnoreCase(resource, ".groovy")) {
// When clearly asking for Groovy, that's what they'll get...
readerClass = GroovyBeanDefinitionReader.class;
}
else {
// Primarily ".xml" files but for any other extension as well
readerClass = XmlBeanDefinitionReader.class;
}
}
// 嘗試重 readerInstanceCache 讀取 BeanDefinitionReader 假如沒有就實例化政模。
BeanDefinitionReader reader = readerInstanceCache.get(readerClass);
if (reader == null) {
try {
// Instantiate the specified BeanDefinitionReader
reader = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry);
// Delegate the current ResourceLoader to it if possible
if (reader instanceof AbstractBeanDefinitionReader) {
AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) reader);
abdr.setResourceLoader(this.resourceLoader);
abdr.setEnvironment(this.environment);
}
readerInstanceCache.put(readerClass, reader);
}
catch (Throwable ex) {
throw new IllegalStateException(
"Could not instantiate BeanDefinitionReader class [" + readerClass.getName() + "]");
}
}
// 加載 bean
// TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations
reader.loadBeanDefinitions(resource);
});
}
主要做了四件事情:
1岗宣、遍歷所有的 importedResources 。
2淋样、選擇 BeanDefinitionReader耗式,假如是 groovy 類,就使用 GroovyBeanDefinitionReader 不是就使用 XmlBeanDefinitionReader
3趁猴、嘗試從readerInstanceCache中獲取對應(yīng)的BeanDefinitionReader,如果不存在,則實例化一個,然后放入到readerInstanceCache緩存中刊咳。
4、調(diào)用 BeanDefinitionReader#loadBeanDefinitions 進(jìn)行加載 bean儡司。
5娱挨、注冊@Import注解中的ImportBeanDefinitionRegistrar接口的registerBeanDefinitions。
private void loadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars) {
registrars.forEach((registrar, metadata) ->
registrar.registerBeanDefinitions(metadata, this.registry, this.importBeanNameGenerator));
}