跳至主要內容

Spring

HeChuangJun约 9045 字大约 30 分钟

spring源码

1. AnnotationConfigApplicationContext extends GenericApplicationContext,AbstractApplicationContext,DefaultResourceLoader

implements AnnotationConfigRegistry,BeanDefinitionRegistry,ConfigurableApplicationContext,AliasRegistry,ApplicationContext,Lifecycle,Closeable
EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,MessageSource, ApplicationEventPublisher, ResourcePatternResolver,BeanFactory,ResourceLoader,AutoCloseable
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry{
private final AnnotatedBeanDefinitionReader reader;

private final ClassPathBeanDefinitionScanner scanner;

public AnnotationConfigApplicationContext() {
	this.reader = new AnnotatedBeanDefinitionReader(this);
	this.scanner = new ClassPathBeanDefinitionScanner(this);
}
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
	this();//创建AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner
	register(annotatedClasses);
	refresh();
}
//GenericApplicationContext 父类构造
private final DefaultListableBeanFactory beanFactory;
public GenericApplicationContext() {
	this.beanFactory = new DefaultListableBeanFactory();//默认创建了BeanFactory
}
//AbstractApplicationContext 父父类构造
private ResourcePatternResolver resourcePatternResolver;
public AbstractApplicationContext() {
	this.resourcePatternResolver = getResourcePatternResolver();
}

protected ResourcePatternResolver getResourcePatternResolver() {
	return new PathMatchingResourcePatternResolver(this);
}

public void register(Class<?>... annotatedClasses) {
	Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
	this.reader.register(annotatedClasses);
}
public void register(Class<?>... annotatedClasses) {
	for (Class<?> annotatedClass : annotatedClasses) {
		registerBean(annotatedClass);
	}
}
public void registerBean(Class<?> annotatedClass) {
	doRegisterBean(annotatedClass, null, null, null);
}
//1.初始化AnnotatedGenericBeanDefinition
//		属性class = 传入的class
// 		属性metadata=StandardAnnotationMetadata 对象 里面的annotations=传入class的所有注解 nestedAnnotationsAsMap = true introspectedClass = 传入的class
//2.shouldSkip判断是否应该跳过,即是否有conditional注解(内部通过Processor接口实现类alwaysTrueAnnotationProcessor的调用searchWithGetSemantics判断返回null确定不跳过)
//3.解析@Scope注解,获取bean的作用域配置信息
//4.解析公共注解Lazy DependsOn Role Description
//5.将启动类注册到beanDefinitionMap中
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
		@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
	AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
	if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
		return;
	}

	abd.setInstanceSupplier(instanceSupplier);
	//解析@Scope注解,获取bean的作用域配置信息
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
	abd.setScope(scopeMetadata.getScopeName());
	String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));//产生BeanName
	//解析公共注解Lazy DependsOn Role Description
	AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
	if (qualifiers != null) {
		for (Class<? extends Annotation> qualifier : qualifiers) {
			if (Primary.class == qualifier) {
				abd.setPrimary(true);
			}
			else if (Lazy.class == qualifier) {
				abd.setLazyInit(true);
			}
			else {
				abd.addQualifier(new AutowireCandidateQualifier(qualifier));
			}
		}
	}
	for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
		customizer.customize(abd);
	}

	BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
	definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
	BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}

}

2. BeanDefinitionReaderUtils

public class BeanDefinitionReaderUtils {
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {

	// Register bean definition under primary name.
	String beanName = definitionHolder.getBeanName();
	registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

	// Register aliases for bean name, if any.
	String[] aliases = definitionHolder.getAliases();
	if (aliases != null) {
		for (String alias : aliases) {
			registry.registerAlias(beanName, alias);
		}
	}
}

}

3. PathMatchingResourcePatternResolver

public class PathMatchingResourcePatternResolver implements ResourcePatternResolver {
private final ResourceLoader resourceLoader;
public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader) {
Assert.notNull(resourceLoader, "ResourceLoader must not be null");
this.resourceLoader = resourceLoader;
}
}

4. DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory,AbstractBeanFactory,FactoryBeanRegistrySupport,DefaultSingletonBeanRegistry,SimpleAliasRegistry

implements ConfigurableListableBeanFactory,ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory,BeanFactory,HierarchicalBeanFactory, SingletonBeanRegistry,AliasRegistry

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
			private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
			private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
			private AutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver();
			private Comparator<Object> dependencyComparator;
			private final Map<String, String> aliasMap = new ConcurrentHashMap<>(16);
			private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256));
			private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);
			/** Cached array of bean definition names in case of frozen configuration */
			private volatile String[] frozenBeanDefinitionNames;

			DefaultListableBeanFactory{}
			//父类DefaultSingletonBeanRegistry
			/** Cache of singleton objects: bean name --> bean instance */
			private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

			/** Cache of singleton factories: bean name --> ObjectFactory */
			private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

			/** Cache of early singleton objects: bean name --> bean instance */
			private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
			//父类AbstractBeanFactory
			@Nullable
			private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
		}

		protected boolean hasBeanCreationStarted() {
			return !this.alreadyCreated.isEmpty();
		}

		public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
			if (beanDefinition instanceof AbstractBeanDefinition) {
				try {
					((AbstractBeanDefinition) beanDefinition).validate();
				}
				catch (BeanDefinitionValidationException ex) {
					throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
							"Validation of bean definition failed", ex);
				}
			}

			BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
			if (existingDefinition != null) {
				this.beanDefinitionMap.put(beanName, beanDefinition);
			}
			else {
				if (hasBeanCreationStarted()) {
					// Cannot modify startup-time collection elements anymore (for stable iteration)
					synchronized (this.beanDefinitionMap) {
						this.beanDefinitionMap.put(beanName, beanDefinition);
						List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
						updatedDefinitions.addAll(this.beanDefinitionNames);
						updatedDefinitions.add(beanName);
						this.beanDefinitionNames = updatedDefinitions;
						if (this.manualSingletonNames.contains(beanName)) {
							Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
							updatedSingletons.remove(beanName);
							this.manualSingletonNames = updatedSingletons;
						}
					}
				}
				else {
					this.beanDefinitionMap.put(beanName, beanDefinition);
					this.beanDefinitionNames.add(beanName);
					this.manualSingletonNames.remove(beanName);
				}
				this.frozenBeanDefinitionNames = null;
			}

			if (existingDefinition != null || containsSingleton(beanName)) {
				resetBeanDefinition(beanName);
			}
			else if (isConfigurationFrozen()) {
				clearByTypeCache();
			}
		}
		public void registerAlias(String name, String alias) {
			synchronized (this.aliasMap) {
				if (alias.equals(name)) {
					this.aliasMap.remove(alias);
				}
				else {
					String registeredName = this.aliasMap.get(alias);
					if (registeredName != null) {
						if (registeredName.equals(name)) {
							return;
						}
						if (!allowAliasOverriding()) {
							throw new IllegalStateException("Cannot define alias '" + alias + "' for name '" +
									name + "': It is already registered for name '" + registeredName + "'.");
						}
					}
					checkForAliasCircle(name, alias);
					this.aliasMap.put(alias, name);
				}
			}
	}
}

5. AnnotatedBeanDefinitionReader

public class AnnotatedBeanDefinitionReader{
// 1.getOrCreateEnvironment判断registry是否实现了ConfigurableEnvironment接口,没有实现环境的接口的话返回默认实现的环境StandardEnvironment
// 2.(1)将registry赋值给当前对象
//(2)给当前对象创建conditionEvaluator(
// conditionEvaluator对象初始化属性 ConditionContextImpl
//registry 直接赋值
// resourceLoader : 取出传递的resourceLoader(null)的ClassLoader或者是beanFactory的BeanClassLoader,最后才返回getDefaultClassLoader
// beanfactory属性:取出ConfigurableListableBeanFactory接口或ConfigurableApplicationContext接口的BeanFactory)
// 取出实现EnvironmentCapable接口的environment,否则使用StandardEnvironment
//取出ResourceLoader接口的资源配置类,否则使用DefaultResourceLoader
//(3)给当前对象registry注册AnnotationConfigProcessors
//将registry强转为DefaultListableBeanFactory并设置AnnotationAwareOrderComparator和ContextAnnotationAutowireCandidateResolver属性
//将org.springframework.context.annotation.internalConfigurationAnnotationProcessor//注解后置处理器open in new window
//org.springframework.context.annotation.internalAutowiredAnnotationProcessoropen in new window"
//org.springframework.context.annotation.internalRequiredAnnotationProcessoropen in new window
//org.springframework.context.annotation.internalCommonAnnotationProcessoropen in new window
//org.springframework.context.event.internalEventListenerProcessoropen in new window
//org.springframework.context.event.internalEventListenerFactoryopen in new window
// 放入到registry中
private final BeanDefinitionRegistry registry;
private ConditionEvaluator conditionEvaluator;
private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();
private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, getOrCreateEnvironment(registry));
}

public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	Assert.notNull(environment, "Environment must not be null");
	this.registry = registry;
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
	AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);//将AnnotationConfigProcessors封装成RootBeanDefinition放入BeanFactory
}

//判断registry是否实现了ConfigurableEnvironment接口,没有实现环境的接口的话返回默认实现的环境StandardEnvironment
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	if (registry instanceof EnvironmentCapable) {
		//由于AnnotationConfigApplicationContext实现了EnvironmentCapable从这里返回
		//默认使用StandardEnvironment
		return ((EnvironmentCapable) registry).getEnvironment();
	}
	return new StandardEnvironment();
}

}

6. ConditionEvaluator

class ConditionEvaluator{
private final ConditionContextImpl context;
public ConditionEvaluator(@Nullable BeanDefinitionRegistry registry,@Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {
this.context = new ConditionContextImpl(registry, environment, resourceLoader);//resourceLoader=null
}
private static class ConditionContextImpl implements ConditionContext {
private final BeanDefinitionRegistry registry;
private final ConfigurableListableBeanFactory beanFactory;
private final Environment environment;
private final ResourceLoader resourceLoader;
private final ClassLoader classLoader;
public ConditionContextImpl(@Nullable BeanDefinitionRegistry registry,@Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {
this.registry = registry;
this.beanFactory = deduceBeanFactory(registry);
this.environment = (environment != null ? environment : deduceEnvironment(registry));
this.resourceLoader = (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry));
this.classLoader = deduceClassLoader(resourceLoader, this.beanFactory);
}
}
//取出ConfigurableListableBeanFactory接口或ConfigurableApplicationContext接口的BeanFactory,否则为null
private ConfigurableListableBeanFactory deduceBeanFactory(@Nullable BeanDefinitionRegistry source) {
if (source instanceof ConfigurableListableBeanFactory) {
return (ConfigurableListableBeanFactory) source;
}
if (source instanceof ConfigurableApplicationContext) {
return (((ConfigurableApplicationContext) source).getBeanFactory());由于AnnotationConfigApplicationContext实现了ConfigurableApplicationContext从这里返回
}
return null;
}
//取出EnvironmentCapable接口的environment,否则使用StandardEnvironment
private Environment deduceEnvironment(@Nullable BeanDefinitionRegistry source) {
if (source instanceof EnvironmentCapable) {
return ((EnvironmentCapable) source).getEnvironment();由于AnnotationConfigApplicationContext实现了EnvironmentCapable从这里返回
}
return new StandardEnvironment();
}
//取出ResourceLoader接口的资源配置类,否则使用DefaultResourceLoader
private ResourceLoader deduceResourceLoader(@Nullable BeanDefinitionRegistry source) {
if (source instanceof ResourceLoader) {
return (ResourceLoader) source;//由于AnnotationConfigApplicationContext实现了ResourceLoader从这里返回
}
return new DefaultResourceLoader();
}

//取出BeanFactory的classLoader,否则使用DefaultClassLoader
private ClassLoader deduceClassLoader(@Nullable ResourceLoader resourceLoader,@Nullable ConfigurableListableBeanFactory beanFactory) {
	if (resourceLoader != null) {
		ClassLoader classLoader = resourceLoader.getClassLoader();
		if (classLoader != null) {
			return classLoader;
		}
	}
	if (beanFactory != null) {
		return beanFactory.getBeanClassLoader();//resourceLoader为null从这里返回
	}
	return ClassUtils.getDefaultClassLoader();
}
public boolean shouldSkip(AnnotatedTypeMetadata metadata) {
	return shouldSkip(metadata, null);
}
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;
}

}

7. AnnotationConfigUtils

public class AnnotationConfigUtils{
	public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
		registerAnnotationConfigProcessors(registry, null);
	}
	public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) {
		//取出DefaultListableBeanFactory
		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		//设置类的加载顺序和自动加载解决者
		if (beanFactory != null) {
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);//为null自动写入
			}
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());//
			}
		}

		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
		//添加一堆BeanPostProcessors(RootBeanDefinition)
		if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
		if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
		if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition();
			try {
				def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
						AnnotationConfigUtils.class.getClassLoader()));
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
			}
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
		}

		if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
		}

		return beanDefs;
	}

	private static DefaultListableBeanFactory unwrapDefaultListableBeanFactory(BeanDefinitionRegistry registry) {
		if (registry instanceof DefaultListableBeanFactory) {
			return (DefaultListableBeanFactory) registry;
		}
		else if (registry instanceof GenericApplicationContext) {
			return ((GenericApplicationContext) registry).getDefaultListableBeanFactory();//由于AnnotationConfigApplicationContext实现了GenericApplicationContext
		}
		else {
			return null;
		}
	}

	//注册基础的registry并返回BeanDefinitionHolder
	private static BeanDefinitionHolder registerPostProcessor(BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {
		definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		registry.registerBeanDefinition(beanName, definition);
		return new BeanDefinitionHolder(definition, beanName);
	}
	
	//将注解里面的method封装为AnnotationAttributes对象然后key为method的Name,Value为ValueHolder
	static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, Class<?> annotationClass) {
		return attributesFor(metadata, annotationClass.getName());
	}
	static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, String annotationClassName) {
		return AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annotationClassName, false));
	}

	public static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd) {
		processCommonDefinitionAnnotations(abd, abd.getMetadata());
	}

	static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {
		AnnotationAttributes lazy = attributesFor(metadata, Lazy.class);
		if (lazy != null) {
			abd.setLazyInit(lazy.getBoolean("value"));
		}
		else if (abd.getMetadata() != metadata) {
			lazy = attributesFor(abd.getMetadata(), Lazy.class);
			if (lazy != null) {
				abd.setLazyInit(lazy.getBoolean("value"));
			}
		}

		if (metadata.isAnnotated(Primary.class.getName())) {
			abd.setPrimary(true);
		}
		AnnotationAttributes dependsOn = attributesFor(metadata, DependsOn.class);
		if (dependsOn != null) {
			abd.setDependsOn(dependsOn.getStringArray("value"));
		}

		if (abd instanceof AbstractBeanDefinition) {
			AbstractBeanDefinition absBd = (AbstractBeanDefinition) abd;
			AnnotationAttributes role = attributesFor(metadata, Role.class);
			if (role != null) {
				absBd.setRole(role.getNumber("value").intValue());
			}
			AnnotationAttributes description = attributesFor(metadata, Description.class);
			if (description != null) {
				absBd.setDescription(description.getString("value"));
			}
		}
	}

	static BeanDefinitionHolder applyScopedProxyMode(ScopeMetadata metadata, BeanDefinitionHolder definition, BeanDefinitionRegistry registry) {

		ScopedProxyMode scopedProxyMode = metadata.getScopedProxyMode();
		if (scopedProxyMode.equals(ScopedProxyMode.NO)) {
			return definition;
		}
		boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS);
		return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass);
	}
}

8. ScopedProxyCreator

class ScopedProxyCreator {

public static BeanDefinitionHolder createScopedProxy(
		BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry, boolean proxyTargetClass) {

	return ScopedProxyUtils.createScopedProxy(definitionHolder, registry, proxyTargetClass);
}

public static String getTargetBeanName(String originalBeanName) {
	return ScopedProxyUtils.getTargetBeanName(originalBeanName);
}

}

9. ScopedProxyUtils

public abstract class ScopedProxyUtils {
public static BeanDefinitionHolder createScopedProxy(BeanDefinitionHolder definition,
BeanDefinitionRegistry registry, boolean proxyTargetClass) {

	String originalBeanName = definition.getBeanName();
	BeanDefinition targetDefinition = definition.getBeanDefinition();
	String targetBeanName = getTargetBeanName(originalBeanName);

	// Create a scoped proxy definition for the original bean name,
	// "hiding" the target bean in an internal target definition.
	RootBeanDefinition proxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class);
	proxyDefinition.setDecoratedDefinition(new BeanDefinitionHolder(targetDefinition, targetBeanName));
	proxyDefinition.setOriginatingBeanDefinition(targetDefinition);
	proxyDefinition.setSource(definition.getSource());
	proxyDefinition.setRole(targetDefinition.getRole());

	proxyDefinition.getPropertyValues().add("targetBeanName", targetBeanName);
	if (proxyTargetClass) {
		targetDefinition.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
		// ScopedProxyFactoryBean's "proxyTargetClass" default is TRUE, so we don't need to set it explicitly here.
	}
	else {
		proxyDefinition.getPropertyValues().add("proxyTargetClass", Boolean.FALSE);
	}

	// Copy autowire settings from original bean definition.
	proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
	proxyDefinition.setPrimary(targetDefinition.isPrimary());
	if (targetDefinition instanceof AbstractBeanDefinition) {
		proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition);
	}

	// The target bean should be ignored in favor of the scoped proxy.
	targetDefinition.setAutowireCandidate(false);
	targetDefinition.setPrimary(false);

	// Register the target bean as separate bean in the factory.
	registry.registerBeanDefinition(targetBeanName, targetDefinition);

	// Return the scoped proxy definition as primary bean definition
	// (potentially an inner bean).
	return new BeanDefinitionHolder(proxyDefinition, originalBeanName, definition.getAliases());
}

}

10. ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider implements EnvironmentCapable, ResourceLoaderAware,Aware

public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider{

private final BeanDefinitionRegistry registry;
private final List<TypeFilter> includeFilters = new LinkedList<>();
//初始化对象当前属性
//1. useDefaultFilters = true 同时注册给当前includeFilters注册两个 javax.annotation.ManagedBean 和javax.inject.Named 两个 AnnotationTypeFilter
//2. environment = getOrCreateEnvironment判断registry是否实现了ConfigurableEnvironment接口,没有实现环境的接口的话返回默认实现的环境StandardEnvironment
//3. ResourceLoader =   registry是否实现ResourceLoader,否则为null
//4. registry = 传过来的registry
//5.this.includeFilter注册两个filter javax.annotation.ManagedBean和javax.inject.Named
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
	this(registry, true);
}
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) {
	this(registry, useDefaultFilters, getOrCreateEnvironment(registry));
}
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,Environment environment) {
	this(registry, useDefaultFilters, environment,(registry instanceof ResourceLoader ? (ResourceLoader) registry : null));
}
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,Environment environment, @Nullable ResourceLoader resourceLoader) {
	this.registry = registry;
	if (useDefaultFilters) {
		registerDefaultFilters();
	}
	setEnvironment(environment);
	setResourceLoader(resourceLoader);
}
protected void registerDefaultFilters() {
	this.includeFilters.add(new AnnotationTypeFilter(Component.class));
	ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
	try {
		this.includeFilters.add(new AnnotationTypeFilter(((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
	}
	catch (ClassNotFoundException ex) {}
	try {
		this.includeFilters.add(new AnnotationTypeFilter(((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
	}
	catch (ClassNotFoundException ex) {}
}
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	if (registry instanceof EnvironmentCapable) {
		return ((EnvironmentCapable) registry).getEnvironment();
	}
	return new StandardEnvironment();
}

}

11. AnnotatedGenericBeanDefinition extends GenericBeanDefinition,AbstractBeanDefinition,BeanMetadataAttributeAccessor,AttributeAccessorSupport implements AnnotatedBeanDefinition ,BeanMetadataElement,BeanDefinition, Cloneable,AttributeAccessor, BeanMetadataElement,Serializable

public class AnnotatedGenericBeanDefinition extends GenericBeanDefinition implements AnnotatedBeanDefinition {
@Nullable
private volatile Object beanClass;
public AnnotatedGenericBeanDefinition(Class<?> beanClass) {
setBeanClass(beanClass);
this.metadata = new StandardAnnotationMetadata(beanClass, true);
}
}

12. StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata,ClassMetadata,AnnotatedTypeMetadata

public class StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata{
private final Annotation[] annotations;

private final boolean nestedAnnotationsAsMap;
public StandardAnnotationMetadata(Class<?> introspectedClass, boolean nestedAnnotationsAsMap) {

	super(introspectedClass);
	this.annotations = introspectedClass.getAnnotations();
	this.nestedAnnotationsAsMap = nestedAnnotationsAsMap;
}
public boolean isAnnotated(String annotationName) {
	return (this.annotations.length > 0 &&
			AnnotatedElementUtils.isAnnotated(getIntrospectedClass(), annotationName));
}
//父类
private final Class<?> introspectedClass;
public StandardClassMetadata(Class<?> introspectedClass) {
	Assert.notNull(introspectedClass, "Class must not be null");
	this.introspectedClass = introspectedClass;
}

public Map<String, Object> getAnnotationAttributes(String annotationName, boolean classValuesAsString) {
	return (this.annotations.length > 0 ? AnnotatedElementUtils.getMergedAnnotationAttributes(
			getIntrospectedClass(), annotationName, classValuesAsString, this.nestedAnnotationsAsMap) : null);
}

}

13. AnnotatedElementUtils

public class AnnotatedElementUtils {
	public static boolean isAnnotated(AnnotatedElement element, String annotationName) {
		return Boolean.TRUE.equals(searchWithGetSemantics(element, null, annotationName, alwaysTrueAnnotationProcessor));
	}
	private interface Processor<T> {

		/**
		 * Process the supplied annotation.
		 * <p>The supplied annotation will be an actual target annotation
		 * that has been found by the search algorithm, unless this processor
		 * is configured to {@linkplain #alwaysProcesses always process}
		 * annotations in which case it may be some other annotation within an
		 * annotation hierarchy. In the latter case, the {@code metaDepth}
		 * will have a value greater than {@code 0}. In any case, it is
		 * up to concrete implementations of this method to decide what to
		 * do with the supplied annotation.
		 * <p>The {@code metaDepth} parameter represents the depth of the
		 * annotation relative to the first annotated element in the
		 * annotation hierarchy. For example, an annotation that is
		 * <em>present</em> on a non-annotation element will have a depth
		 * of 0; a meta-annotation will have a depth of 1; and a
		 * meta-meta-annotation will have a depth of 2; etc.
		 * @param annotatedElement the element that is annotated with the
		 * supplied annotation, used for contextual logging; may be
		 * {@code null} if unknown
		 * @param annotation the annotation to process
		 * @param metaDepth the meta-depth of the annotation
		 * @return the result of the processing, or {@code null} to continue
		 * searching for additional annotations
		 */
		@Nullable
		T process(@Nullable AnnotatedElement annotatedElement, Annotation annotation, int metaDepth);

		/**
		 * Post-process the result returned by the {@link #process} method.
		 * <p>The {@code annotation} supplied to this method is an annotation
		 * that is present in the annotation hierarchy, between the initial
		 * {@link AnnotatedElement} and an invocation of {@link #process}
		 * that returned a non-null value.
		 * @param annotatedElement the element that is annotated with the
		 * supplied annotation, used for contextual logging; may be
		 * {@code null} if unknown
		 * @param annotation the annotation to post-process
		 * @param result the result to post-process
		 */
		void postProcess(@Nullable AnnotatedElement annotatedElement, Annotation annotation, T result);

		/**
		 * Determine if this processor always processes annotations regardless of
		 * whether or not the target annotation has been found.
		 * @return {@code true} if this processor always processes annotations
		 * @since 4.3
		 */
		boolean alwaysProcesses();

		/**
		 * Determine if this processor aggregates the results returned by {@link #process}.
		 * <p>If this method returns {@code true}, then {@link #getAggregatedResults()}
		 * must return a non-null value.
		 * @return {@code true} if this processor supports aggregated results
		 * @since 4.3
		 * @see #getAggregatedResults
		 */
		boolean aggregates();

		/**
		 * Get the list of results aggregated by this processor.
		 * <p>NOTE: the processor does <strong>not</strong> aggregate the results
		 * itself. Rather, the search algorithm that uses this processor is
		 * responsible for asking this processor if it {@link #aggregates} results
		 * and then adding the post-processed results to the list returned by this
		 * method.
		 * @return the list of results aggregated by this processor (never {@code null})
		 * @since 4.3
		 * @see #aggregates
		 */
		List<T> getAggregatedResults();
	}
	static class AlwaysTrueBooleanAnnotationProcessor extends SimpleAnnotationProcessor<Boolean> {

		@Override
		public final Boolean process(@Nullable AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
			return Boolean.TRUE;
		}
	}

	private static class MergedAnnotationAttributesProcessor implements Processor<AnnotationAttributes> {

		private final boolean classValuesAsString;

		private final boolean nestedAnnotationsAsMap;

		private final boolean aggregates;

		private final List<AnnotationAttributes> aggregatedResults;

		MergedAnnotationAttributesProcessor() {
			this(false, false, false);
		}

		MergedAnnotationAttributesProcessor(boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
			this(classValuesAsString, nestedAnnotationsAsMap, false);
		}

		MergedAnnotationAttributesProcessor(boolean classValuesAsString, boolean nestedAnnotationsAsMap,
				boolean aggregates) {

			this.classValuesAsString = classValuesAsString;
			this.nestedAnnotationsAsMap = nestedAnnotationsAsMap;
			this.aggregates = aggregates;
			this.aggregatedResults = (aggregates ? new ArrayList<>() : Collections.emptyList());
		}

		@Override
		public boolean alwaysProcesses() {
			return false;
		}

		@Override
		public boolean aggregates() {
			return this.aggregates;
		}

		@Override
		public List<AnnotationAttributes> getAggregatedResults() {
			return this.aggregatedResults;
		}

		@Override
		@Nullable
		public AnnotationAttributes process(@Nullable AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
			return AnnotationUtils.retrieveAnnotationAttributes(annotatedElement, annotation,
					this.classValuesAsString, this.nestedAnnotationsAsMap);
		}

		@Override
		public void postProcess(@Nullable AnnotatedElement element, Annotation annotation, AnnotationAttributes attributes) {
			annotation = AnnotationUtils.synthesizeAnnotation(annotation, element);
			Class<? extends Annotation> targetAnnotationType = attributes.annotationType();

			// Track which attribute values have already been replaced so that we can short
			// circuit the search algorithms.
			Set<String> valuesAlreadyReplaced = new HashSet<>();

			for (Method attributeMethod : AnnotationUtils.getAttributeMethods(annotation.annotationType())) {
				String attributeName = attributeMethod.getName();
				String attributeOverrideName = AnnotationUtils.getAttributeOverrideName(attributeMethod, targetAnnotationType);

				// Explicit annotation attribute override declared via @AliasFor
				if (attributeOverrideName != null) {
					if (valuesAlreadyReplaced.contains(attributeOverrideName)) {
						continue;
					}

					List<String> targetAttributeNames = new ArrayList<>();
					targetAttributeNames.add(attributeOverrideName);
					valuesAlreadyReplaced.add(attributeOverrideName);

					// Ensure all aliased attributes in the target annotation are overridden. (SPR-14069)
					List<String> aliases = AnnotationUtils.getAttributeAliasMap(targetAnnotationType).get(attributeOverrideName);
					if (aliases != null) {
						for (String alias : aliases) {
							if (!valuesAlreadyReplaced.contains(alias)) {
								targetAttributeNames.add(alias);
								valuesAlreadyReplaced.add(alias);
							}
						}
					}

					overrideAttributes(element, annotation, attributes, attributeName, targetAttributeNames);
				}
				// Implicit annotation attribute override based on convention
				else if (!AnnotationUtils.VALUE.equals(attributeName) && attributes.containsKey(attributeName)) {
					overrideAttribute(element, annotation, attributes, attributeName, attributeName);
				}
			}
		}

		private void overrideAttributes(@Nullable AnnotatedElement element, Annotation annotation,
				AnnotationAttributes attributes, String sourceAttributeName, List<String> targetAttributeNames) {

			Object adaptedValue = getAdaptedValue(element, annotation, sourceAttributeName);

			for (String targetAttributeName : targetAttributeNames) {
				attributes.put(targetAttributeName, adaptedValue);
			}
		}

		private void overrideAttribute(@Nullable AnnotatedElement element, Annotation annotation,
				AnnotationAttributes attributes, String sourceAttributeName, String targetAttributeName) {

			attributes.put(targetAttributeName, getAdaptedValue(element, annotation, sourceAttributeName));
		}

		@Nullable
		private Object getAdaptedValue(
				@Nullable AnnotatedElement element, Annotation annotation, String sourceAttributeName) {

			Object value = AnnotationUtils.getValue(annotation, sourceAttributeName);
			return AnnotationUtils.adaptValue(element, value, this.classValuesAsString, this.nestedAnnotationsAsMap);
		}
	}

	private static <T> T searchWithGetSemantics(AnnotatedElement element,
			@Nullable Class<? extends Annotation> annotationType,
			@Nullable String annotationName, Processor<T> processor) {

		return searchWithGetSemantics(element, annotationType, annotationName, null, processor);
	}
	private static <T> T searchWithGetSemantics(AnnotatedElement element,
			@Nullable Class<? extends Annotation> annotationType, @Nullable String annotationName,
			@Nullable Class<? extends Annotation> containerType, Processor<T> processor) {

		try {
			return searchWithGetSemantics(element, annotationType, annotationName, containerType, processor,
					new HashSet<>(), 0);
		}
		catch (Throwable ex) {
			AnnotationUtils.rethrowAnnotationConfigurationException(ex);
			throw new IllegalStateException("Failed to introspect annotations on " + element, ex);
		}
	}
	// 在提供的注释列表中进行实际搜索。应该先用本地声明的注释调用该方法,然后再用继承的注释调用,从而允许本地注释优先于继承的注释。
	// ①记录已经访问的注解(用set防止重复)重复则不执行
	// ②调用searchWithGetSemanticsInAnnotations返回结果
	// ③没有结果就找当前类的父类的所有注解,调用searchWithGetSemanticsInAnnotations返回结果,再没有结果就返回null
	//总结:调用searchWithGetSemanticsInAnnotations解析当前注解返回结果(true或者是AnnotationAttributes暂时发现),结果为null,则继续找父注解,直到无结果返回
	private static <T> T searchWithGetSemantics(AnnotatedElement element,
			@Nullable Class<? extends Annotation> annotationType, @Nullable String annotationName,
			@Nullable Class<? extends Annotation> containerType, Processor<T> processor,
			Set<AnnotatedElement> visited, int metaDepth) {

		if (visited.add(element)) {
			try {
				// Start searching within locally declared annotations
				List<Annotation> declaredAnnotations = Arrays.asList(element.getDeclaredAnnotations());
				T result = searchWithGetSemanticsInAnnotations(element, declaredAnnotations,
						annotationType, annotationName, containerType, processor, visited, metaDepth);
				if (result != null) {
					return result;
				}

				if (element instanceof Class) {  // otherwise getAnnotations doesn't return anything new
					Class<?> superclass = ((Class) element).getSuperclass();
					if (superclass != null && superclass != Object.class) {
						List<Annotation> inheritedAnnotations = new LinkedList<>();
						for (Annotation annotation : element.getAnnotations()) {
							if (!declaredAnnotations.contains(annotation)) {
								inheritedAnnotations.add(annotation);
							}
						}
						// Continue searching within inherited annotations
						result = searchWithGetSemanticsInAnnotations(element, inheritedAnnotations,
								annotationType, annotationName, containerType, processor, visited, metaDepth);
						if (result != null) {
							return result;
						}
					}
				}
			}
			catch (Throwable ex) {
				AnnotationUtils.handleIntrospectionFailure(element, ex);
			}
		}

		return null;
	}
	@Nullable
	// 在提供的注释列表中进行实际搜索。应该先用本地声明的注释调用该方法,然后再用继承的注释调用,从而允许本地注释优先于继承的注释。
	// ①遍历提供的注解,如果是spring的注解就调用processor接口的实现返回结果并记录总结果
	// ②再次遍历提供的注解,如果是spring的注解,那么调用searchWithGetSemantics解析结果并记录总结果
		//searchWithGetSemantics实现
		// ①记录已经访问的注解(用set防止重复)重复则不执行
		// ②调用searchWithGetSemanticsInAnnotations返回结果
		// ③没有结果就找当前类的父类的所有注解,调用searchWithGetSemanticsInAnnotations返回结果,再没有结果就返回null
		//总结:调用searchWithGetSemanticsInAnnotations解析当前注解返回结果,结果为null,则继续找父注解,直到无结果返回
	private static <T> T searchWithGetSemanticsInAnnotations(@Nullable AnnotatedElement element,
			List<Annotation> annotations, @Nullable Class<? extends Annotation> annotationType,
			@Nullable String annotationName, @Nullable Class<? extends Annotation> containerType,
			Processor<T> processor, Set<AnnotatedElement> visited, int metaDepth) {

		// Search in annotations
		for (Annotation annotation : annotations) {
			Class<? extends Annotation> currentAnnotationType = annotation.annotationType();
			if (!AnnotationUtils.isInJavaLangAnnotationPackage(currentAnnotationType)) {//判断是否是jdk本身的注解
				if (currentAnnotationType == annotationType ||
						currentAnnotationType.getName().equals(annotationName) ||
						processor.alwaysProcesses()) {
					T result = processor.process(element, annotation, metaDepth);
					if (result != null) {
						if (processor.aggregates() && metaDepth == 0) {
							processor.getAggregatedResults().add(result);
						}
						else {
							return result;
						}
					}
				}
				// Repeatable annotations in container?
				else if (currentAnnotationType == containerType) {
					for (Annotation contained : getRawAnnotationsFromContainer(element, annotation)) {
						T result = processor.process(element, contained, metaDepth);
						if (result != null) {
							// No need to post-process since repeatable annotations within a
							// container cannot be composed annotations.
							//不需要进行后处理,因为容器内的可重复注释不能组成注释
							processor.getAggregatedResults().add(result);
						}
					}
				}
			}
		}

		// Recursively search in meta-annotations
		//递归搜索元注解
		for (Annotation annotation : annotations) {
			Class<? extends Annotation> currentAnnotationType = annotation.annotationType();
			if (hasSearchableMetaAnnotations(currentAnnotationType, annotationType, annotationName)) {//根据传入的三个类型判断是不是Spring本身的注解
				T result = searchWithGetSemantics(currentAnnotationType, annotationType,
						annotationName, containerType, processor, visited, metaDepth + 1);
				if (result != null) {
					processor.postProcess(element, annotation, result);
					if (processor.aggregates() && metaDepth == 0) {
						processor.getAggregatedResults().add(result);
					}
					else {
						return result;
					}
				}
			}
		}

		return null;
	}
		@Nullable
	//获得合并的注解
	// MergedAnnotationAttributesProcessor
	//将注解里面所有的方法合并 成key为MethodName,value为holdler或者String最后//处理别名
	public static AnnotationAttributes getMergedAnnotationAttributes(AnnotatedElement element,
			String annotationName, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {

		AnnotationAttributes attributes = searchWithGetSemantics(element, null, annotationName,
				new MergedAnnotationAttributesProcessor(classValuesAsString, nestedAnnotationsAsMap));
		AnnotationUtils.postProcessAnnotationAttributes(element, attributes, classValuesAsString, nestedAnnotationsAsMap);
		return attributes;
	}
}

14. AnnotationScopeMetadataResolver implements ScopeMetadataResolver

public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver {
private final ScopedProxyMode defaultProxyMode;

public AnnotationScopeMetadataResolver() {
	this.defaultProxyMode = ScopedProxyMode.NO;
}
//解析Scope的注解
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
	ScopeMetadata metadata = new ScopeMetadata();
	if (definition instanceof AnnotatedBeanDefinition) {
		AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
		AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(
				annDef.getMetadata(), this.scopeAnnotationType);//获得Scope所有的方法及属性值
		if (attributes != null) {
			metadata.setScopeName(attributes.getString("value"));
			ScopedProxyMode proxyMode = attributes.getEnum("proxyMode");
			if (proxyMode == ScopedProxyMode.DEFAULT) {
				proxyMode = this.defaultProxyMode;
			}
			metadata.setScopedProxyMode(proxyMode);
		}
	}
	return metadata;
}

}

15. AnnotationBeanNameGenerator

public class AnnotationBeanNameGenerator implements BeanNameGenerator {
		@Override
	public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
		if (definition instanceof AnnotatedBeanDefinition) {
			String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition);
			if (StringUtils.hasText(beanName)) {
				// Explicit bean name found.
				return beanName;
			}
		}
		// Fallback: generate a unique default bean name.
		return buildDefaultBeanName(definition, registry);
	}
	@Nullable
	//从注解上决定Bean名字,从所有的属性里面读出value,如果没有则返回null
	protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
		AnnotationMetadata amd = annotatedDef.getMetadata();
		Set<String> types = amd.getAnnotationTypes();
		String beanName = null;
		for (String type : types) {
			AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(amd, type);
			if (attributes != null && isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
				Object value = attributes.get("value");
				if (value instanceof String) {
					String strVal = (String) value;
					if (StringUtils.hasLength(strVal)) {
						if (beanName != null && !strVal.equals(beanName)) {
							throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
									"component names: '" + beanName + "' versus '" + strVal + "'");
						}
						beanName = strVal;
					}
				}
			}
		}
		return beanName;
	}

	protected String buildDefaultBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
		return buildDefaultBeanName(definition);
	}

	/**
	 * Derive a default bean name from the given bean definition.
	 * <p>The default implementation simply builds a decapitalized version
	 * of the short class name: e.g. "mypackage.MyJdbcDao" -> "myJdbcDao".
	 * <p>Note that inner classes will thus have names of the form
	 * "outerClassName.InnerClassName", which because of the period in the
	 * name may be an issue if you are autowiring by name.
	 * @param definition the bean definition to build a bean name for
	 * @return the default bean name (never {@code null})
	 */
	protected String buildDefaultBeanName(BeanDefinition definition) {
		String beanClassName = definition.getBeanClassName();
		Assert.state(beanClassName != null, "No bean class name set");
		String shortClassName = ClassUtils.getShortName(beanClassName);
		return Introspector.decapitalize(shortClassName);
	}
}

16. BeanDefinitionHolder implements BeanMetadataElement

public class BeanDefinitionHolder implements BeanMetadataElement {
public BeanDefinitionHolder(BeanDefinition beanDefinition, String beanName) {
this(beanDefinition, beanName, null);
}
public BeanDefinitionHolder(BeanDefinition beanDefinition, String beanName, @Nullable String[] aliases) {
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
Assert.notNull(beanName, "Bean name must not be null");
this.beanDefinition = beanDefinition;
this.beanName = beanName;
this.aliases = aliases;
}
}

17. ClassUtils

public abstract class ClassUtils {
private static final char PACKAGE_SEPARATOR = '.';
private static final char INNER_CLASS_SEPARATOR = ';/TheCGLIBclassseparator:""/publicstaticfinalStringCGLIBCLASSSEPARATOR="$";

public static String getShortName(String className) {
	Assert.hasLength(className, "Class name must not be empty");
	int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
	int nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);
	if (nameEndIndex == -1) {
		nameEndIndex = className.length();
	}
	String shortName = className.substring(lastDotIndex + 1, nameEndIndex);
	shortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);
	return shortName;
}

public static String getShortName(String className) {
	Assert.hasLength(className, "Class name must not be empty");
	int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
	int nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);
	if (nameEndIndex == -1) {
		nameEndIndex = className.length();
	}
	String shortName = className.substring(lastDotIndex + 1, nameEndIndex);
	shortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);
	return shortName;
}

}

18. Introspector

public class Introspector {
public static String decapitalize(String name) {
if (name == null || name.length() == 0) {
return name;
}
if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
Character.isUpperCase(name.charAt(0))){
return name;
}
char chars[] = name.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}
}

19. AnnotationConfigApplicationContext创建流程

  • 创建AnnotationConfigApplicationContext

    • 属性ResourcePatternResolver resourcePatternResolver:new PathMatchingResourcePatternResolver(this);(AbstractApplicationContext构造)
      • 属性ResourceLoader resourceLoader:AnnotationConfigApplicationContext:DefaultResourceLoader
    • 属性ClassLoader classLoader:AppClassLoader();(DefaultResourceLoader构造)
    • 属性DefaultListableBeanFactory beanFactory:new DefaultListableBeanFactory();(GenericApplicationContext构造)
      • 属性Comparator<Object> dependencyComparator: new AnnotationAwareOrderComparator();//排序BeanPostprocessor
      • 属性AutowireCandidateResolver autowireCandidateResolver:new ContextAnnotationAutowireCandidateResolver();
      • 属性Map<String,BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256)
        • RootBeanDefinition(ConfigurationClassPostProcessor.class implements BeanDefinitionRegistryPostProcessor): internalConfigurationAnnotationProcessor//注解后置处理器
        • RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class): internalAutowiredAnnotationProcessor
        • RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class): internalRequiredAnnotationProcessor
        • RootBeanDefinition(CommonAnnotationBeanPostProcessor.class): internalCommonAnnotationProcessor
        • RootBeanDefinition(EventListenerMethodProcessor.class): internalEventListenerProcessor
        • RootBeanDefinition(DefaultEventListenerFactory.class): internalEventListenerFactory
      • 属性List<String> beanDefinitionNames = new ArrayList<>(256)
        • "org.springframework.context.annotation.internalConfigurationAnnotationProcessor"//注解后置处理器
        • "org.springframework.context.annotation.internalAutowiredAnnotationProcessor"
        • "org.springframework.context.annotation.internalRequiredAnnotationProcessor"
        • "org.springframework.context.annotation.internalCommonAnnotationProcessor"
        • "org.springframework.context.event.internalEventListenerProcessor"
        • "org.springframework.context.event.internalEventListenerFactory"
    • 属性ConfigurableEnvironment environment:new StandardEnvironment();
    • 属性AnnotatedBeanDefinitionReader reader:new AnnotatedBeanDefinitionReader();
      • 属性BeanDefinitionRegistry registry:AnnotationConfigApplicationContext
      • 属性ConditionEvaluator conditionEvaluator:new ConditionEvaluator();
        • 属性ConditionContextImpl context:new ConditionContextImpl();
          • 属性BeanDefinitionRegistry registry: AnnotationConfigApplicationContext
          • 属性ConfigurableListableBeanFactory beanFactory: DefaultListableBeanFactory
          • 属性Environment environment:StandardEnvironment
          • 属性ResourceLoader resourceLoader:DefaultResourceLoader
          • 属性ClassLoader classLoader:AppClassLoader
      • 属性默认ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver()
      • 属性默认BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator()
    • 属性ClassPathBeanDefinitionScanner scanner:new ClassPathBeanDefinitionScanner()
      • 属性BeanDefinitionRegistry registry:AnnotationConfigApplicationContext
      • 属性List<TypeFilter> includeFilters = new LinkedList<>()
        • new AnnotationTypeFilter(Component.class)
      • 属性Environment environment:StandardEnvironment
      • 属性ResourcePatternResolver resourcePatternResolver:AnnotationConfigApplicationContext(DefaultResourceLoader)
      • 属性MetadataReaderFactory metadataReaderFactory:new CachingMetadataReaderFactory()(属性省略)
  • AnnotatedBeanDefinitionReader.register方法将class注册到DefaultListableBeanFactory的beanDefinitionMap中

    • 构造AnnotatedGenericBeanDefinition
      • 属性beanClass:class
      • 属性AnnotationMetadata metadata:new StandardAnnotationMetadata(beanClass, true)
        • 属性Annotation[] annotations: class.getAnnotations();
        • 属性boolean nestedAnnotationsAsMap:true;
        • 属性Class<?> introspectedClass:class
    • 调用ConditionEvaluator.shouSkip判断是否是conditional注解,若是无需注册
    • 调用scopeMetadataResolver.resolveScopeMetadata判断是否被@Scope注解注解了,并解析Value属性和proxyMode
    • 调用beanNameGenerator.generateBeanName得到BeanName
    • 调用processCommonDefinitionAnnotations判断是否被lazy,Primary,DependsOn,Role,Description注解,给AnnotatedGenericBeanDefinition设置相应的属性
    • 调用AnnotationConfigUtils.applyScopedProxyMode判断是否要是多例的
    • 调用BeanDefinitionReaderUtils.registerBeanDefinition将AnnotatedGenericBeanDefinition注册到DefaultListableBeanFactory的beanDefinitionMap中,注意别名的注册
  • AnnotationConfigApplicationContext的refresh()方法

    • prepareRefresh()

      • 属性long startupDate:System.currentTimeMillis()记录启动时间
      • 属性AtomicBoolean active:true
      • 属性AtomicBoolean closed:false
      • 初始化系统属性initPropertySources钩子方法
      • 使用ConfigurablePropertyResolver校验设置的setRequiredProperties环境参数(getEnvironment().validateRequiredProperties)(没看)
      • 属性Set<ApplicationListener<?>> earlyApplicationListeners:new LinkedHashSet<>();
      • 属性Set<ApplicationEvent> earlyApplicationEvents:new LinkedHashSet<>()
    • ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      • refreshBeanFactory();由于AnnotationConfigApplicationContext继承了GenericApplicationContext,复写了refreshBeanFactory()方法,只给AnnotationConfigApplicationContext的beanFactory设置了一个SerializationId
    • prepareBeanFactory(beanFactory);

      • 给AnnotationConfigApplicationContext的beanFactory设置ClassLoader beanClassLoader:AppClassLoader
      • 给AnnotationConfigApplicationContext的beanFactory设置BeanExpressionResolver beanExpressionResolver:new StandardBeanExpressionResolver(AppClassLoader)
      • 给AnnotationConfigApplicationContext的beanFactory设置Set<PropertyEditorRegistrar> propertyEditorRegistrars:add ResourceEditorRegistrar(StandardEnvironment)

      // Configure the bean factory with context callbacks.

      • 给AnnotationConfigApplicationContext的beanFactory设置List<BeanPostProcessor> beanPostProcessors:
        • add new ApplicationContextAwareProcessor(this)
        • add new ApplicationListenerDetector(this)
      • 给AnnotationConfigApplicationContext的beanFactory设置Set<Class<?>> ignoredDependencyInterfaces:
        • add EnvironmentAware.class
        • add EmbeddedValueResolverAware.class
        • add ResourceLoaderAware.class
        • add ApplicationEventPublisherAware.class
        • add MessageSourceAware.class
        • add ApplicationContextAware.class
      • 给AnnotationConfigApplicationContext的beanFactory设置Map<Class<?>, Object> resolvableDependencies
        • put BeanFactory.class, BeanFactory
        • put ResourceLoader.class, this
        • put ApplicationEventPublisher.class, this
        • put ApplicationContext.class, this
      • if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        // Set a temporary ClassLoader for type matching.
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
        }
      • 给AnnotationConfigApplicationContext的beanFactory设置Map<String,Object> singletonObjects
        • <environment,StandardEnvironment>
        • <systemProperties,properties>,
        • <systemEnvironment,Map>
      • 给AnnotationConfigApplicationContext的beanFactory设置Set<String> registeredSingletons:
        • "environment"
        • "systemProperties"
        • "systemEnvironment"
      • Set<String> manualSingletonNames添加
        • "environment"
        • "systemProperties"
        • "systemEnvironment"
      • 将上一步三个对象放入到singletonObjects
    • postProcessBeanFactory(beanFactory)钩子方法(没看)

    • invokeBeanFactoryPostProcessors(beanFactory)

      • 调用PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors
        • 判断beanFacctory是否实现了BeanDefinitionRegistry接口
          • 创建List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();存放实现了BeanDefinitionRegistryPostProcessor
          • 创建List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();存放实现了BeanDefinitionRegistryPostProcessor
          • 遍历BeanFactoryPostProcessor,找到BeanDefinitionRegistryPostProcessor实现类调用postProcessBeanDefinitionRegistry方法,并放入到registryProcessors中,其他放入regularPostProcessors中
          • 遍历beanFactory中的beanDefinitionNames找到同时实现了BeanDefinitionRegistryPostProcessor.class和PriorityOrdered.class的类,按实现了AnnotationAwareOrderComparator接口进行排序,(这个方法里面找到ConfigurationClassPostProcessor)调用其postProcessBeanDefinitionRegistry实现接口方法
            • ConfigurationClassPostProcessor调用postProcessBeanDefinitionRegistry(本质调用processConfigBeanDefinitions)重点
              • 扫描已经注册的BeanDefinition,找到所有Component、ComponentScan、Import、ImportResource、或者Configuration注解的类并解析order注解,最后按order排序,创建ConfigurationClassParser,并循环做如下解析(本质doProcessConfigurationClass)
                • 解析@PropertySource注解(待看),使用componentScanParser找上面的解析@ComponentScan,解析到那个类之后再doProcessConfigurationClass一遍(递归)
                • 解析@Import、@ImportResource
                • 从配置类@Configuration中解析@Bean,找到的所有类加入到BeanFactory中
                • 创建ConfigurationClassBeanDefinitionReader,找到相关@Bean里面的bean定义,找到@Import的资源加载进来
          • 除了上面的后置处理器外,找到有@orderd注解的重复上面的步骤
          • 找到除了上面2种后置处理器外的接口,重复上面的步骤
          • 调用上面收集到的regularPostProcessors和registryProcessors的postProcessBeanFactory方法
        • 没实现则直接遍历BeanFactoryPostProcessors调用postProcessBeanFactory方法
        • 最后调用除了上面的所有实现了BeanFactoryPostProcessor接口的类,分成priorityOrdered.class\ordered.class\其他\各自排序完成后调用postProcessBeanFactory方法
      • 检查如果搜索到LoadTimeWeaver,需要准备织入
        • if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        • beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        • beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
        • }
    • registerBeanPostProcessors(beanFactory)

      • 找到所有BeanPostProcessor.class的类名字
      • beanFactory的BeanPostProcessor添加BeanPostProcessorChecker
      • 从beanFactory找到实现了BeanPostProcessor.class的类,同时priorityOrdered.class\ordered.class\nonOrdered各自排序,并将其注册到AnnotationConfigApplicationContext的beanPostProcessors中,将上面三种类中同时实现了MergedBeanDefinitionPostProcessor接口的类排序后也注册进去
      • beanFactory的BeanPostProcessor添加ApplicationListenerDetector
    • 初始化国际化initMessageSource();

    • 注册广播initApplicationEventMulticaster()

    • onRefresh()启动别的容器的子类

    • registerListeners()注册监听类

    • finishBeanFactoryInitialization(beanFactory)初始化所有的bean(本质调用preInstantiateSingletons)

      • beanFactory的List<StringValueResolver> embeddedValueResolvers添加getEnvironment().resolvePlaceholders(strVal)(待看)
      • String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
        for (String weaverAwareName : weaverAwareNames) {
        getBean(weaverAwareName);
        }
      • beanFactory.configurationFrozen = true;
      • beanFactory.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);
      • beanFactory.preInstantiateSingletons();
        • 遍历beanDefinitionNames、调用getMergedLocalBeanDefinition判断BeanDefinition当且仅当非抽象类、单例、非懒加载时
          • isFactoryBean()判断是否是FactoryBean实现类(待看)
            • 如果实现了FactoryBean而且是SmartFactoryBean类型且isEagerInit,则getBean初始化
          • 当不是FactoryBean实现类时,直接getBean初始化
          • getBean(name)->doGetBean(name)方法
            • 如果该name是FactoryBean,那么截取掉&,得到BeanName
            • getSingleton(beanName,true)
            • 如果getSingleton!=null,getObjectForBeanInstance();(待看)
            • 如果getSingleton==null,第一次进来
              • 如果prototypesCurrentlyInCreation找到它,则抛出循环依赖的异常
              • 从mergedBeanDefinitions查找,没有则从父容器中doGetBean继续找
              • 如果是typeCheckOnly->添加到Set<String> alreadyCreated
              • 并将其他的BeanDefinition、GenericBeanDefinition转成RootBeanDefinition(getMergedBeanDefinition())
              • 判断BeanDefinition的dependsOn关系,如果dependentBeanMap中有则抛出循环依赖异常,否则记录到dependentBeanMap并getBean找到对应的类
              • 如果是单例,调用getSingleton(beanName,CreatBean());
                • 复制RootBeanDefinition,遍历MethodOverrides调用prepareMethodOverrides,(解析@ Lookup和lookup-method标签得到的)
                • 自定义Bean的调用——遍历BeanPostProcessor中实现InstantiationAwareBeanPostProcessor的类,调用postProcessBeforeInstantiation创建对象,如果有对象则调用postProcessAfterInitialization,如果没有的话,就执行doCreateBean由spring产生
                  • 通过createBeanInstance获得BeanWrapper
                    • 从父类中拿到实例(待看)
                    • 从FactoryMethod中拿到实例(待看)
                    • 判断是否有@AutoWired相关的,找到则autowireConstructor(待看)
                    • 没有与@AutoWired相关的,调用SimpleInstantiationStrategy.instantiateBean通过反射创建(待看)
                  • 将resolvedTargetType赋给RootBeanDefinition的resolvedTargetType
                  • 遍历BeanPostProcessor中实现了MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法,并将其postProcessed置为true
                  • 如果是allowCircularReferences、singletonsCurrentlyInCreation、单例的情况下,先放入到singletonFactories、registeredSingletons、移走earlySingletonObjects三级缓存中防止循环依赖
                  • populateBean:填充属性
                    • 如果含有InstantiationAwareBeanPostProcessors且非synthetic合成,则遍历BeanPostProcessors调用InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation
                    • 判断@AutoWired属性并且完成属性注入(待看)
                    • initializeBean:初始化属性
                    • 非合成类则遍历BeanPostProcessor调用postProcessBeforeInitialization
                    • 非合成类则遍历BeanPostProcessor调用postProcessAfterInitialization
                  • registerDisposableBeanIfNecessary();(待看)
              • 如果是多例(待看)
              • 其他情况(待看)
              • 最后大家都调用getObjectForBeanInstance(判断是否实现了FactoryBean,不是FactoryBean直接返回传入的对象)(待看)
        • 遍历beanDefinitionNames调用实现了SmartInitializingSingleton接口bean的afterSingletonsInstantiated方法
  • 解析XML

  • resourcePatternResolver().getResources(location)->new ClassPathContextResource(location) implements Resource ->new EncodedResource(Resource) implements InputStreamSource
    ->classLoader.getResourceAsStream Inputstream ->InputSource->DOMParser.Document

  • PathMatchingResourcePatternResolver解析basePackage

  • Enumeration<URL> classLoder.getResource() ->Set<Resource>

20. Spring AnnotatedElementUtils遍历搜索注解的属性的方法

//搜索本注解及其父类的@inherited注解的集合
private static <T> T searchWithGetSemantics(
	AnnotatedElement element,//含有注解的类
	@Nullable Class<? extends Annotation> annotationType, 
	@Nullable String annotationName,
	@Nullable Class<? extends Annotation> containerType, //可重复注解的容器对象(暂时看全部都是为null,功能未知)
	Processor<T> processor,//实现了Processor接口的接口类,通过Processor来对元素进行处理
	Set<AnnotatedElement> visited, //已经访问的元素:用set防止重复,并终止递归
	int metaDepth//注解深度,控制注解收集,processor只收集第一次拿到的结果
	) {
	if (visited.add(element)) {
		try {
			List<Annotation> declaredAnnotations = Arrays.asList(element.getDeclaredAnnotations());
			T result = searchWithGetSemanticsInAnnotations(element, declaredAnnotations,
				annotationType, annotationName, containerType, processor, visited, metaDepth);
			if (result != null) {return result;}
			if (element instanceof Class) {  // otherwise getAnnotations doesn't return anything new
				Class<?> superclass = ((Class) element).getSuperclass();
				if (superclass != null && superclass != Object.class) {
					List<Annotation> inheritedAnnotations = new LinkedList<>();
					for (Annotation annotation : element.getAnnotations()) {//拿到从父类继承过来的@inherited注解再找一遍
						if (!declaredAnnotations.contains(annotation)) {
							inheritedAnnotations.add(annotation);
						}
					}
					// Continue searching within inherited annotations
					result = searchWithGetSemanticsInAnnotations(element, inheritedAnnotations,
					annotationType, annotationName, containerType, processor, visited, metaDepth);
					if (result != null) {
						return result;
					}
				}
			}
		}
		catch (Throwable ex) {
			AnnotationUtils.handleIntrospectionFailure(element, ex);
		}
	}

	return null;
}
//搜索本注解及其注解的注解
private static <T> T searchWithGetSemanticsInAnnotations(
	@Nullable AnnotatedElement element,//含有注解的类
	List<Annotation> annotations, //被搜索的注解列表
	@Nullable Class<? extends Annotation> annotationType,//需要搜索的注解
	@Nullable String annotationName, //需要搜索的注解的全类名
	@Nullable Class<? extends Annotation> containerType,//可重复注解的容器对象(暂时看全部都是为null,功能未知)
	Processor<T> processor, //实现了Processor接口的接口类,通过Processor来对元素进行处理
	Set<AnnotatedElement> visited, //已经访问的元素:用set防止重复,并终止递归
	int metaDepth //注解深度,控制注解收集,processor只收集第一次拿到的结果
	) {

		for (Annotation annotation : annotations) {
			Class<? extends Annotation> currentAnnotationType = annotation.annotationType();
			//判断是否是jdk本身的注解:currentAnnotationType.getName()判断是否是java.lang.annotation开头
			if (!AnnotationUtils.isInJavaLangAnnotationPackage(currentAnnotationType)) {
				//判断类型一致,全类名一致、或者Processor接口alwaysProcesses决定必须执行process
				if (currentAnnotationType == annotationType ||
					currentAnnotationType.getName().equals(annotationName) ||
					processor.alwaysProcesses()) {
					T result = processor.process(element, annotation, metaDepth);
					if (result != null) {
						//Processor接口aggregates和metaDepth为0是决定是否要收集结果到processor
						if (processor.aggregates() && metaDepth == 0) {
							processor.getAggregatedResults().add(result);
						}
						else {
							return result;
						}
					}
				}
				// Repeatable annotations in container?
				//全部为null,基本没啥用这个方法,功能未知,可能是@Repeatable注解?
				else if (currentAnnotationType == containerType) {
					for (Annotation contained : getRawAnnotationsFromContainer(element, annotation)) {
						T result = processor.process(element, contained, metaDepth);
						if (result != null) {
							processor.getAggregatedResults().add(result);
						}
					}
				}
			}
		}

		//递归搜索注解上的注解,递归搜索元注解,然后调用过postProcess后置处理
		for (Annotation annotation : annotations) {
			Class<? extends Annotation> currentAnnotationType = annotation.annotationType();
			//currentAnnotationType不是java.lang.annotation开头,annotationType, annotationName不是以java开头
			if (hasSearchableMetaAnnotations(currentAnnotationType, annotationType, annotationName)) {
				//递归搜索注解上的注解
				T result = searchWithGetSemantics(currentAnnotationType, annotationType,
						annotationName, containerType, processor, visited, metaDepth + 1);
				if (result != null) {
					//调用processor的后置处理结果处理结果
					processor.postProcess(element, annotation, result);
					//Processor接口aggregates和metaDepth为0是决定是否要收集结果到processor
					if (processor.aggregates() && metaDepth == 0) {
						processor.getAggregatedResults().add(result);
					}
					else {
						return result;
					}
				}
			}
		}

		return null;
	}
Processor接口实现类之一 MergedAnnotationAttributesProcessor
private static class MergedAnnotationAttributesProcessor implements Processor<AnnotationAttributes> {
		private final boolean classValuesAsString;
		private final boolean nestedAnnotationsAsMap;
		private final boolean aggregates;
		private final List<AnnotationAttributes> aggregatedResults;

		MergedAnnotationAttributesProcessor() {this(false, false, false);}

		MergedAnnotationAttributesProcessor(boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
			this(classValuesAsString, nestedAnnotationsAsMap, false);
		}

		MergedAnnotationAttributesProcessor(boolean classValuesAsString, 
			boolean nestedAnnotationsAsMap, boolean aggregates) {
			this.classValuesAsString = classValuesAsString;
			this.nestedAnnotationsAsMap = nestedAnnotationsAsMap;
			this.aggregates = aggregates;
			this.aggregatedResults = (aggregates ? new ArrayList<>() : Collections.emptyList());
		}

		@Override
		public boolean alwaysProcesses() {return false;}

		@Override
		public boolean aggregates() {return this.aggregates;}

		@Override
		public List<AnnotationAttributes> getAggregatedResults() {
			return this.aggregatedResults;
		}

		@Override
		@Nullable
		public AnnotationAttributes process(@Nullable AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
			return AnnotationUtils.retrieveAnnotationAttributes(annotatedElement, annotation,
					this.classValuesAsString, this.nestedAnnotationsAsMap);
		}

		@Override
		public void postProcess(@Nullable AnnotatedElement element, Annotation annotation, AnnotationAttributes attributes) {
			annotation = AnnotationUtils.synthesizeAnnotation(annotation, element);
			Class<? extends Annotation> targetAnnotationType = attributes.annotationType();

			// Track which attribute values have already been replaced so that we can short
			// circuit the search algorithms.
			Set<String> valuesAlreadyReplaced = new HashSet<>();

			for (Method attributeMethod : AnnotationUtils.getAttributeMethods(annotation.annotationType())) {
				String attributeName = attributeMethod.getName();
				String attributeOverrideName = AnnotationUtils.getAttributeOverrideName(attributeMethod, targetAnnotationType);

				// Explicit annotation attribute override declared via @AliasFor
				if (attributeOverrideName != null) {
					if (valuesAlreadyReplaced.contains(attributeOverrideName)) {
						continue;
					}

					List<String> targetAttributeNames = new ArrayList<>();
					targetAttributeNames.add(attributeOverrideName);
					valuesAlreadyReplaced.add(attributeOverrideName);

					// Ensure all aliased attributes in the target annotation are overridden. (SPR-14069)
					List<String> aliases = AnnotationUtils.getAttributeAliasMap(targetAnnotationType).get(attributeOverrideName);
					if (aliases != null) {
						for (String alias : aliases) {
							if (!valuesAlreadyReplaced.contains(alias)) {
								targetAttributeNames.add(alias);
								valuesAlreadyReplaced.add(alias);
							}
						}
					}

					overrideAttributes(element, annotation, attributes, attributeName, targetAttributeNames);
				}
				// Implicit annotation attribute override based on convention
				else if (!AnnotationUtils.VALUE.equals(attributeName) && attributes.containsKey(attributeName)) {
					overrideAttribute(element, annotation, attributes, attributeName, attributeName);
				}
			}
		}
	}
AnnotationUtils
//检索注解里面的方法并返回AnnotationAttributes(非常常用)
static AnnotationAttributes retrieveAnnotationAttributes(
	@Nullable Object annotatedElement, 
	Annotation annotation,
	boolean classValuesAsString, 
	boolean nestedAnnotationsAsMap
	) {

	Class<? extends Annotation> annotationType = annotation.annotationType();
	AnnotationAttributes attributes = new AnnotationAttributes(annotationType);

	for (Method method : getAttributeMethods(annotationType)) {
		try {
			Object attributeValue = method.invoke(annotation);
			Object defaultValue = method.getDefaultValue();
			if (defaultValue != null && ObjectUtils.nullSafeEquals(attributeValue, defaultValue)) {
				attributeValue = new DefaultValueHolder(defaultValue);
			}
			attributes.put(method.getName(),
					adaptValue(annotatedElement, attributeValue, classValuesAsString, nestedAnnotationsAsMap));
		}
		catch (Throwable ex) {
			if (ex instanceof InvocationTargetException) {
				Throwable targetException = ((InvocationTargetException) ex).getTargetException();
				rethrowAnnotationConfigurationException(targetException);
			}
			throw new IllegalStateException("Could not obtain annotation attribute value for " + method, ex);
		}
	}

	return attributes;
}

//先从缓存里面去,没有则取出与传入接口的所有相关方法并设置为允许访问,最后把结果以 key 为annotationType 值为List<Method> attributeMethodsCache缓存起来,
static List<Method> getAttributeMethods(Class<? extends Annotation> annotationType) {
	List<Method> methods = attributeMethodsCache.get(annotationType);
	if (methods != null) {return methods;}
	methods = new ArrayList<>();
	for (Method method : annotationType.getDeclaredMethods()) {
		//(method != null && method.getParameterCount() == 0 && method.getReturnType() != void.class);
		if (isAttributeMethod(method)) {//判断是否是注解的方法
			ReflectionUtils.makeAccessible(method);
			methods.add(method);
		}
	}

	attributeMethodsCache.put(annotationType, methods);
	return methods;
}

spring三级缓存
DefaultSingletonBeanRegistry
//从singletonObjects找
	// 在singletonsCurrentlyInCreation的单例,从earlySingletonObjects中找
	// allowEarlyReference,那么从singletonFactories找,并将对象singletonFactories放到earlySingletonObjects中
	protected Object getSingleton(String beanName, boolean allowEarlyReference) {
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
			synchronized (this.singletonObjects) {
				singletonObject = this.earlySingletonObjects.get(beanName);
				if (singletonObject == null && allowEarlyReference) {
					ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
					if (singletonFactory != null) {
						singletonObject = singletonFactory.getObject();
						this.earlySingletonObjects.put(beanName, singletonObject);
						this.singletonFactories.remove(beanName);
					}
				}
			}
		}
		return singletonObject;
	}
//从mergedBeanDefinitions中找到RootBeanDefinition
	protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
		RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
		if (mbd != null) {return mbd;}
		return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));//getBeanDefinition从beanDefinitionMap找BeanDefinition
	}
	protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
		throws BeanDefinitionStoreException {
		return getMergedBeanDefinition(beanName, bd, null);
	}
	//如果给定bean的定义是子bean定义,则通过与父bean合并返回给定bean的RootBeanDefinition
	//在mergedBeanDefinitions找->RootBeanDefinition类型则复制,否则之间创建
	// ->从父容器的ConfigurableBeanFactory得到getMergedBeanDefinition,构造RootBeanDefinition,设置Scope
	//缓存到mergedBeanDefinitions
	protected RootBeanDefinition getMergedBeanDefinition(
			String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
			throws BeanDefinitionStoreException {

		synchronized (this.mergedBeanDefinitions) {
			RootBeanDefinition mbd = null;
			if (containingBd == null) {
				mbd = this.mergedBeanDefinitions.get(beanName);
			}

			if (mbd == null) {
				if (bd.getParentName() == null) {
					if (bd instanceof RootBeanDefinition) {
						mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
					}
					else {
						mbd = new RootBeanDefinition(bd);
					}
				}
				else {
					// Child bean definition: needs to be merged with parent.
					BeanDefinition pbd;
					try {
						String parentBeanName = transformedBeanName(bd.getParentName());
						if (!beanName.equals(parentBeanName)) {
							pbd = getMergedBeanDefinition(parentBeanName);
						}
						else {
							BeanFactory parent = getParentBeanFactory();
							if (parent instanceof ConfigurableBeanFactory) {
								pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
							}
							else {
								throw new NoSuchBeanDefinitionException(parentBeanName,
										"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
										"': cannot be resolved without a ConfigurableBeanFactory parent");
							}
						}
					}
					catch (NoSuchBeanDefinitionException ex) {
						throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
								"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
					}
					// Deep copy with overridden values.
					mbd = new RootBeanDefinition(pbd);
					mbd.overrideFrom(bd);
				}

				// Set default singleton scope, if not configured before.
				if (!StringUtils.hasLength(mbd.getScope())) {
					mbd.setScope(SCOPE_SINGLETON);
				}

				// A bean contained in a non-singleton bean cannot be a singleton itself.
				// Let's correct this on the fly here, since this might be the result of
				// parent-child merging for the outer bean, in which case the original inner bean
				// definition will not have inherited the merged outer bean's singleton status.
				if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
					mbd.setScope(containingBd.getScope());
				}

				// Cache the merged bean definition for the time being
				// (it might still get re-merged later on in order to pick up metadata changes)
				if (containingBd == null && isCacheBeanMetadata()) {
					this.mergedBeanDefinitions.put(beanName, mbd);
				}
			}

			return mbd;
		}
	}
ClassUtils中计算class及其父类的所有符合的method的个数
public static int getMethodCountForName(Class<?> clazz, String methodName) {
		Assert.notNull(clazz, "Class must not be null");
		Assert.notNull(methodName, "Method name must not be null");
		int count = 0;
		Method[] declaredMethods = clazz.getDeclaredMethods();
		for (Method method : declaredMethods) {
			if (methodName.equals(method.getName())) {
				count++;
			}
		}
		Class<?>[] ifcs = clazz.getInterfaces();
		for (Class<?> ifc : ifcs) {
			count += getMethodCountForName(ifc, methodName);
		}
		if (clazz.getSuperclass() != null) {
			count += getMethodCountForName(clazz.getSuperclass(), methodName);
		}
		return count;
	}
public class RootBeanDefinition extends AbstractBeanDefinition,BeanMetadataAttributeAccessor,AttributeAccessorSupport
	implements BeanDefinition,Cloneable,BeanMetadataElement,AttributeAccessor,Serializable{
	
	//RootBeanDefinition
	private BeanDefinitionHolder decoratedDefinition;
	private AnnotatedElement qualifiedElement;
	boolean allowCaching = true;
	boolean isFactoryMethodUnique = false;
	volatile ResolvableType targetType;
	volatile Class<?> resolvedTargetType;//包可见的字段,用于缓存给定bean定义的确定类
	volatile ResolvableType factoryMethodReturnType;//包可见字段,用于缓存泛型工厂方法的返回类型

	final Object constructorArgumentLock = new Object();下面四个构造函数字段的公共锁
	Executable resolvedConstructorOrFactoryMethod;//包可见字段,用于缓存已解析的构造函数或工厂方法
	boolean constructorArgumentsResolved = false;//包可见的字段,将构造函数参数标记为已解析
	Object[] resolvedConstructorArguments;//包可见的字段,用于缓存完全解析的构造函数参数
	Object[] preparedConstructorArguments;//包可见的字段,用于缓存部分准备的构造函数参数

	final Object postProcessingLock = new Object();//下面两个后处理字段的通用锁
	boolean postProcessed = false;//包可见的字段,指示已经应用了MergedBeanDefinitionPostProcessor
	volatile Boolean beforeInstantiationResolved;//包可见字段,指示实例化前的后处理程序已经启动

	private Set<Member> externallyManagedConfigMembers;
	private Set<String> externallyManagedInitMethods;
	private Set<String> externallyManagedDestroyMethods;

	//AbstractBeanDefinition
	private String scope = SCOPE_DEFAULT;
	public static final String SCOPE_DEFAULT = "";//@Scope相关,除非被父bean定义覆盖,否则等同于单例状态
	public static final int AUTOWIRE_NO = AutowireCapableBeanFactory.AUTOWIRE_NO;//常数,表示根本没有外部自动装配
	public static final int AUTOWIRE_BY_NAME = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;//常量,按名称指示自动装配bean属性
	public static final int AUTOWIRE_BY_TYPE = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;//按类型指示自动装配bean属性的常量
	public static final int AUTOWIRE_CONSTRUCTOR = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;//常量,指示自动装配构造函数
	@Deprecated
	public static final int AUTOWIRE_AUTODETECT = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;//常量,指示通过bean类的内省来确定适当的自动装配策略

	public static final int DEPENDENCY_CHECK_NONE = 0;//表示根本没有依赖项检查的常量
	public static final int DEPENDENCY_CHECK_OBJECTS = 1;//常量,指示对对象引用进行依赖项检查
	public static final int DEPENDENCY_CHECK_SIMPLE = 2;//常量,指示对“简单”属性的依赖项检查
	public static final int DEPENDENCY_CHECK_ALL = 3;//常量,指示对所有属性进行依赖项检查
	public static final String INFER_METHOD = "(inferred)";//常量,指示容器应该尝试推断bean的销毁方法名,而不是显式地指定方法名 
	//@Value专门设计为在方法名中包含否则不合法的字符 确保与具有相同名称的合法命名方法不发生冲突


	private volatile Object beanClass;
	private boolean abstractFlag = false;
	private boolean lazyInit = false;
	private int autowireMode = AUTOWIRE_NO;
	private int dependencyCheck = DEPENDENCY_CHECK_NONE;
	private String[] dependsOn;

	private boolean autowireCandidate = true;//是否被认为是自动类型装配,不影响名字装配
	private boolean primary = false;//优先被依赖的类@primary/primary标签
	private final Map<String, AutowireCandidateQualifier> qualifiers = new LinkedHashMap<>();
	private Supplier<?> instanceSupplier;
	private boolean nonPublicAccessAllowed = true;
	private boolean lenientConstructorResolution = true;//使多个构造函数的参数数量相同、类型存在父子类、接口实现类关系也能正常创建bean

	private String factoryBeanName;
	private String factoryMethodName;

	private ConstructorArgumentValues constructorArgumentValues;
	private MutablePropertyValues propertyValues;
	private MethodOverrides methodOverrides = new MethodOverrides();//@lookup/<lookup-method>

	private String initMethodName;//<init-method>/@PostConstruct(java自己的注解)
	private String destroyMethodName;//<destroy-method>/@PreDestroy(java自己的注解)
	private boolean enforceInitMethod = true;//是否执行init-method,程序设置
	private boolean enforceDestroyMethod = true;//是否执行destroy-method,程序设置
	
	private boolean synthetic = false;//非应用自己定义的,类似Aop产生的对象

	private int role = BeanDefinition.ROLE_APPLICATION;
	//BeanDefinition
	int ROLE_APPLICATION = 0;//用户定义的bean
	int ROLE_SUPPORT = 1;//指示BeanDefinition是某个较大配置(通常是外部组件定义)的支持部分。
	int ROLE_INFRASTRUCTURE = 2;//内部注册的bean类似internalConfigurationAnnotationProcessor
	//------------

	private String description;//@Description或者<description>
	private Resource resource;//来源的文件

	//BeanMetadataAttributeAccessor-----------------------------------------------------------------
	private Object source;
	
	//AttributeAccessorSupport-----------------------------------------------------------------
	/** Map with String keys and Object values */
	private final Map<String, Object> attributes = new LinkedHashMap<>();

	}