spring 源码解析一(bean定义)

本文内容纲要:

- new AnnotationConfigApplicationContext ()做了哪些事

- 1首先调用父类的构造器,创建了ioc容器

- 2然后调用本身类的无参构造器

- 3注册配置类到容器中 register(annotatedClasses);

- 4 refresh()方法

spring容器的创建

public class MainClass {

public static void main(String[] args) {

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);

}

}

new AnnotationConfigApplicationContext ()做了哪些事

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {

//调用无参构造器,会调用父类的无参构造器

this();

//注册配置类

register(annotatedClasses);

//容器刷新

refresh();

}

1首先调用父类的构造器,创建了ioc容器

public GenericApplicationContext() {

//创建了spring容器,DefaultListableBeanFactory是真正可以作为一个可以独立使用的ioc容器

this.beanFactory = new DefaultListableBeanFactory();

}

2然后调用本身类的无参构造器

public AnnotationConfigApplicationContext() {

//为IOC容器赋值 AnnotatedBeanDefinitionReader(注解的Bean定义读取器)

this.reader = new AnnotatedBeanDefinitionReader(this);

//为IOC容器赋值 类路径下的bean定义扫描器

this.scanner = new ClassPathBeanDefinitionScanner(this);

}

2.1 new AnnotatedBeanDefinitionReader(this)

public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {

//getOrCreateEnvironment创建环境

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);

//为容器中注册系统的bean定义信息

AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);

}

2.1.1注册bean定义信息的一些处理器

public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {

registerAnnotationConfigProcessors(registry, null);

}

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(

BeanDefinitionRegistry registry, Object source) {

//获取ioc容器

DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);

if (beanFactory != null) {

//设置默认的排序器

if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {

beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);

}

//ContextAnnotationAutoireCandidateResovler用于确定特定的Bean定义是否符合特定的依赖项的候选者

//具体分析可见 https://blog.csdn.net/f641385712/article/details/93620967

if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {

beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());

}

}

Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<BeanDefinitionHolder>(8);

if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {

//注册一个配置类解析器的bean定义(ConfigurationClassPostProcessor)

//该类实现了BeanDefinitionRegistryPostProcessor,

//在refresh方法中的invokeBeanFactoryPostProcessors的方法中会被调用

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)) {

//设置AutoWired注解解析器的bean定义信息 (AutowiredAnnotationBeanPostProcessor)

//该类实现了InstantiationAwareBeanPostProcessor,

//在实例化前后会被调用,自动注入autoire注解的类

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)) {

// 注册解析@Required 注解的处理器

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)) {

//检查是否支持JSR250规范,如何支持注册 解析JSR250规范的注解

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();

//检查是否支持jpa,若支持注册解析jpa规范的注解

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)) {

//注册解析@EventListener的注解

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;

}

2.2 new ClassPathBeanDefinitionScanner(this)

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, ResourceLoader resourceLoader) {

Assert.notNull(registry, "BeanDefinitionRegistry must not be null");

this.registry = registry;

//使用默认的代码扫描规则

if (useDefaultFilters) {

registerDefaultFilters();

}

//设置环境

setEnvironment(environment);

//设置资源加载器

setResourceLoader(resourceLoader);

}

这里虽然新建了一个扫描器,但是实际运用的时候还是重新new了一个,不过程序员在写代码的时候可以从容器中获取这个扫描器。

3注册配置类到容器中 register(annotatedClasses);

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) {

registerBean(annotatedClass, null, (Class<? extends Annotation>[]) null);

}

public void registerBean(Class<?> annotatedClass, String name, Class<? extends Annotation>... qualifiers) {

AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);

if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {

return;

}

ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);

abd.setScope(scopeMetadata.getScopeName());

String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));

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));

}

}

}

//注册自己传入的主配置类bean定义到容器中

BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);

definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);

BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);

}

4 refresh()方法

public void refresh() throws BeansException, IllegalStateException {

synchronized (this.startupShutdownMonitor) {

// Prepare this context for refreshing.

prepareRefresh();

// Tell the subclass to refresh the internal bean factory.

ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// Prepare the bean factory for use in this context.

prepareBeanFactory(beanFactory);

try {

// Allows post-processing of the bean factory in context subclasses.

postProcessBeanFactory(beanFactory);

// Invoke factory processors registered as beans in the context.

invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.

registerBeanPostProcessors(beanFactory);

// Initialize message source for this context.

initMessageSource();

// Initialize event multicaster for this context.

initApplicationEventMulticaster();

// Initialize other special beans in specific context subclasses.

onRefresh();

// Check for listener beans and register them.

registerListeners();

// Instantiate all remaining (non-lazy-init) singletons.

finishBeanFactoryInitialization(beanFactory);

// Last step: publish corresponding event.

finishRefresh();

}

catch (BeansException ex) {

if (logger.isWarnEnabled()) {

logger.warn("Exception encountered during context initialization - " +

"cancelling refresh attempt: " + ex);

}

// Destroy already created singletons to avoid dangling resources.

destroyBeans();

// Reset 'active' flag.

cancelRefresh(ex);

// Propagate exception to caller.

throw ex;

}

finally {

// Reset common introspection caches in Spring's core, since we

// might not ever need metadata for singleton beans anymore...

resetCommonCaches();

}

}

}

refresh方法中包含12步,内容众多,先只分析和bean定义相关的,后续再分析其他内容

4.1 invokeBeanFactoryPostProcessors(beanFactory)

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {

PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime

// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)

if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {

beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));

beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));

}

}

4.2 PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()

public static void invokeBeanFactoryPostProcessors(

ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

//这时候传进来的beanFactoryPostProcessors为null

// Invoke BeanDefinitionRegistryPostProcessors first, if any.

Set<String> processedBeans = new HashSet<String>();

//DefaultListableBeanFactory继承了BeanDefinitionRegistry,所以会走进此分支

if (beanFactory instanceof BeanDefinitionRegistry) {

BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

//创建一个普通的BeanfactoryPostProcessors的list的组件

List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();

//创建一个BeanDefinitionRegistryPostProcessor类型的list

//BeanDefinitionRegistryPostProcessor是继承了BeanFactoryPostProcessor的

List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();

//处理容器硬编码(new 出来的)带入的beanFacotryPostProcessors

//分别放入上面的相对应的集合中

for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {

if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {

BeanDefinitionRegistryPostProcessor registryProcessor =

(BeanDefinitionRegistryPostProcessor) postProcessor;

registryProcessor.postProcessBeanDefinitionRegistry(registry);

registryProcessors.add(registryProcessor);

}

else {

regularPostProcessors.add(postProcessor);

}

}

// Do not initialize FactoryBeans here: We need to leave all regular beans

// uninitialized to let the bean factory post-processors apply to them!

// Separate between BeanDefinitionRegistryPostProcessors that implement

// PriorityOrdered, Ordered, and the rest.

//创建一个当前注册的RegistryProcessors的集合

List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();

// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.

//第一步:去容器中查询是否有BeanDefinitionRegistryPostProcessor类型的,实现了PriorityOrdered接口的,优先级最高

//此时ConfigurationClassPostProcessor被查询出来,ConfigurationClassPostProcessor实现了PriorityOrdered,但是优先级最低

String[] postProcessorNames =

beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

for (String ppName : postProcessorNames) {

if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {

currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));

//加到已处理的list中

processedBeans.add(ppName);

}

}

//排序当前的RegistryProcessors的集合

sortPostProcessors(currentRegistryProcessors, beanFactory);

//注册RegistryProcessors的集合

registryProcessors.addAll(currentRegistryProcessors);

//触发当前的registryProcessors

//ConfigurationClassPostProcessor在这里会被触发

invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);

//清除处理过的

currentRegistryProcessors.clear();

// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.

//第二步:去容器中查询是否有BeanDefinitionRegistryPostProcessor类型的,实现了Ordered接口的,优先级最高

postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

for (String ppName : postProcessorNames) {

if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {

currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));

processedBeans.add(ppName);

}

}

sortPostProcessors(currentRegistryProcessors, beanFactory);

registryProcessors.addAll(currentRegistryProcessors);

invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);

currentRegistryProcessors.clear();

// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.

//第三步:调用普通的BeanDefinitionRegistryPostProcessors没用实现PriorithOrdered和Ordered接口

boolean reiterate = true;

while (reiterate) {

reiterate = false;

postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

for (String ppName : postProcessorNames) {

if (!processedBeans.contains(ppName)) {

currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));

processedBeans.add(ppName);

reiterate = true;

}

}

sortPostProcessors(currentRegistryProcessors, beanFactory);

registryProcessors.addAll(currentRegistryProcessors);

invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);

currentRegistryProcessors.clear();

}

// Now, invoke the postProcessBeanFactory callback of all processors handled so far.

//调用上面查询出来的Processor,也实现了BeanFactoryPostProcessors的接口,调用该接口的方法

invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);

invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);

}

else {

// Invoke factory processors registered with the context instance.

//如果beanFactory不是BeanDefinitionRegistry的对象,直接调用BeanFactoryPostProcessor的方法

invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);

}

// Do not initialize FactoryBeans here: We need to leave all regular beans

// uninitialized to let the bean factory post-processors apply to them!

//下面的是处理BeanFactoryPostProcessor接口的实现类,跟上面逻辑一样,先处理实现PrioityOrdered接口的,然后再处理Ordered接口的,然后再处理普通的

String[] postProcessorNames =

beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,

// Ordered, and the rest.

List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();

List<String> orderedPostProcessorNames = new ArrayList<String>();

List<String> nonOrderedPostProcessorNames = new ArrayList<String>();

for (String ppName : postProcessorNames) {

if (processedBeans.contains(ppName)) {

// skip - already processed in first phase above

}

else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {

priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));

}

else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {

orderedPostProcessorNames.add(ppName);

}

else {

nonOrderedPostProcessorNames.add(ppName);

}

}

// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.

sortPostProcessors(priorityOrderedPostProcessors, beanFactory);

invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

// Next, invoke the BeanFactoryPostProcessors that implement Ordered.

List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();

for (String postProcessorName : orderedPostProcessorNames) {

orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));

}

sortPostProcessors(orderedPostProcessors, beanFactory);

invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

// Finally, invoke all other BeanFactoryPostProcessors.

List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();

for (String postProcessorName : nonOrderedPostProcessorNames) {

nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));

}

invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

// Clear cached merged bean definitions since the post-processors might have

// modified the original metadata, e.g. replacing placeholders in values...

beanFactory.clearMetadataCache();

}

可以看出BeanDefinitionRegistryPostProcessor的执行时机在BeanFactoryPostProcessor之前,

两个类自己的执行首先执行PriorityOrdered修饰的,然后执行Ordered,最后执行普通的

4.3 ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry()

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);

}

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {

List<BeanDefinitionHolder> configCandidates = new ArrayList<>();

//没有解析之前,系统候选的bean定义配置(有自己的配置类,还有系统自带的)

String[] candidateNames = registry.getBeanDefinitionNames();

//循环Bean定义的名称 找出自己的传入的主配置类的bean定义信息

for (String beanName : candidateNames) {

BeanDefinition beanDef = registry.getBeanDefinition(beanName);

//判断是不是配置类

if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||

ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {

if (logger.isDebugEnabled()) {

logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);

}

}

else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {

configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));

}

}

// Return immediately if no @Configuration classes were found

if (configCandidates.isEmpty()) {

return;

}

// Sort by previously determined @Order value, if applicable

//检查配置类排序

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

//配置bean的名称生成策略

SingletonBeanRegistry sbr = null;

if (registry instanceof SingletonBeanRegistry) {

sbr = (SingletonBeanRegistry) registry;

if (!this.localBeanNameGeneratorSet) {

BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);

if (generator != null) {

this.componentScanBeanNameGenerator = generator;

this.importBeanNameGenerator = generator;

}

}

}

if (this.environment == null) {

this.environment = new StandardEnvironment();

}

// Parse each @Configuration class

//创建组件扫描器

//metadataReaderFactory元数据工厂

//problemReporter问题报告器

//

ConfigurationClassParser parser = new ConfigurationClassParser(

this.metadataReaderFactory, this.problemReporter, this.environment,

this.resourceLoader, this.componentScanBeanNameGenerator, registry);

//将需要解析的类加入集合中

Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);

//创建已处理候选类集合,集合大小为候选类大小

Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());

//循环处理候选配置类

do {

//解析配置类

parser.parse(candidates);

//进行校验

parser.validate();

//获取ConfigClass (把解析过的配置bean定义信息获取出来)

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());

}

//@CompentScan是直接注册Bean定义信息的,但是通过获取@Import,@Bean这种的注解还没有注册的bean定义,

this.reader.loadBeanDefinitions(configClasses);

//把系统解析过我们自己的组件放在alreadyParsed

alreadyParsed.addAll(configClasses);

//清除解析过的类

candidates.clear();

//已经注册的bean定义个数大于最新 开始系统+主配置类的(发生过解析)

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();

}

}

4.4 ConfigurationClassParser.parse(Set configCandidates)

public void parse(Set<BeanDefinitionHolder> configCandidates) {

this.deferredImportSelectors = new LinkedList<DeferredImportSelectorHolder>();

for (BeanDefinitionHolder holder : configCandidates) {

BeanDefinition bd = holder.getBeanDefinition();

try {

//这里根据Bean定义的不同类型走不同的分支,但是最终都会调用到方法

//processConfigurationClass(ConfigurationClass configClass)

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);

}

}

processDeferredImportSelectors();

}

4.4.1 ConfigurationClassParser.processConfigurationClass()

protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {

processConfigurationClass(new ConfigurationClass(metadata, beanName));

}

protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {

//检查当前解析的配置bean是否包含Conditional注解,如果不包含则不需要跳过

// 如果包含了则进行match方法得到匹配结果,如果是符合的并且设置的配置解析策略是解析阶段不需要调过

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);

for (Iterator<ConfigurationClass> it = this.knownSuperclasses.values().iterator(); it.hasNext();) {

if (configClass.equals(it.next())) {

it.remove();

}

}

}

}

// Recursively process the configuration class and its superclass hierarchy.

SourceClass sourceClass = asSourceClass(configClass);

//递归解析

do {

sourceClass = doProcessConfigurationClass(configClass, sourceClass);

}

while (sourceClass != null);

// 添加到ConfigurationClassParser的configurationClasses中

this.configurationClasses.put(configClass, configClass);

}

4.4.2 ConfigurationClassParser#doProcessConfigurationClass

1.处理内部类

2.处理@PropertySource注解

3.处理@ComponentScan注解

4.处理@Import注解

5.处理@ImportResource注解

6.处理@Bean修饰的方法

7.处理接口定义的方法

8.处理父类

protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)

throws IOException {

// Recursively process any member (nested) classes first

//处理内部类

processMemberClasses(configClass, sourceClass);

// Process any @PropertySource annotations

//处理@PropertySource注解

// @PropertySource注解用来加载properties文件

for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(

sourceClass.getMetadata(), PropertySources.class,

org.springframework.context.annotation.PropertySource.class)) {

if (this.environment instanceof ConfigurableEnvironment) {

processPropertySource(propertySource);

}

else {

logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +

"]. Reason: Environment must implement ConfigurableEnvironment");

}

}

// Process any @ComponentScan annotations

//处理@ComponentScan注解

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

// 处理@Import注解

//这里面处理了@ImportSelector的bean定义,但是@ImportBeanDefinitionRegistar的只是将类放到了配置中

processImports(configClass, sourceClass, getImports(sourceClass), true);

// Process any @ImportResource annotations

// 处理@ImportResource 注解

if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) {

AnnotationAttributes importResource =

AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);

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

//处理@Bean修饰的方法

Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);

for (MethodMetadata methodMetadata : beanMethods) {

//这里还未注册bean定义,只是将@bean修饰的方法加入配置中,

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.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;

}

4.4.3 ComponentScanAnnotationParser#parse

public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {

// 创建 ClassPathBeanDefinitionScanner

// 在 AnnotationConfigApplicationContext 的构造器中也创建了一个ClassPathBeanDefinitionScanner

// 这里证明了,执行扫描 scanner 不是构造器中的,而是这里创建的

ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,

componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);

// @ComponentScan 中可以注册自定义的 BeanNameGenerator

// 但是需要注意,通过源码可以明白,这里注册的自定义BeanNameGenerator 只对当前 scanner 有效

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);

}

// @ComponentScan(basePackageClasses = Xx.class)

// 可以指定basePackageClasses, 只要是与是这几个类所在包及其子包,就可以被Spring扫描

// 经常会用一个空的类来作为basePackageClasses,默认取当前配置类所在包及其子包

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));

}

protected Set<BeanDefinitionHolder> doScan(String... basePackages) {

Assert.notEmpty(basePackages, "At least one base package must be specified");

Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();

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;

}

4.4.4 ConfigurationClassParser.processImports

private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,

Collection<SourceClass> importCandidates, boolean checkForCircularImports) {

if (importCandidates.isEmpty()) {

return;

}

if (checkForCircularImports && isChainedImportOnStack(configClass)) {

this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));

}

else {

this.importStack.push(configClass);

try {

for (SourceClass candidate : importCandidates) {

//ImportSelector处理

if (candidate.isAssignable(ImportSelector.class)) {

// Candidate class is an ImportSelector -> delegate to it to determine imports

Class<?> candidateClass = candidate.loadClass();

ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);

ParserStrategyUtils.invokeAwareMethods(

selector, this.environment, this.resourceLoader, this.registry);

if (this.deferredImportSelectors != null && selector instanceof DeferredImportSelector) {

this.deferredImportSelectors.add(

new DeferredImportSelectorHolder(configClass, (DeferredImportSelector) selector));

}

else {

//调用selectImports方法,找出需要真正导入的类

String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());

Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);

//处理真正到要导入的类,循环处理每个bean定义

processImports(configClass, currentSourceClass, importSourceClasses, false);

}

}

//ImportBeanDefinitionRegistrar处理

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 =

BeanUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class);

ParserStrategyUtils.invokeAwareMethods(

registrar, this.environment, this.resourceLoader, this.registry);

//这里并未处理,只是将ImportBeanDefinitionRegistrar的实现类加入配置中,接着往下看,是否会调用他的registerBeanDefinitions方法导入bean定义

//事实上是在this.reader.loadBeanDefinitions(configClasses)中处理

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));

}

}

}

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();

}

}

}

4.5 this.reader.loadBeanDefinitions(configClasses);

4.3分析了parse方法, 但是可以看出来上面@ImportBeanDefinitionRegistrar和@Bean和@ImportResource犯法的bean定义并未注册,只是讲这些配置放到了成员变量中,这些bean定义都是在ader.loadBeanDefinitions中注册的,继续往下分析

public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {

TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator();

for (ConfigurationClass configClass : configurationModel) {

loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);

}

}

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;

}

//判断主配置类是不是Improt导入的

if (configClass.isImported()) {

registerBeanDefinitionForImportedConfigurationClass(configClass);

}

//处理@Bean的bean定义

for (BeanMethod beanMethod : configClass.getBeanMethods()) {

loadBeanDefinitionsForBeanMethod(beanMethod);

}

//处理@ImportResource配置的bean定义

loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());

//处理@ImportBeanDefinitionRegistrar的bean定义

loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());

}

本文内容总结:new AnnotationConfigApplicationContext ()做了哪些事,1首先调用父类的构造器,创建了ioc容器,2然后调用本身类的无参构造器,3注册配置类到容器中 register(annotatedClasses);,4 refresh()方法,

原文链接:https://www.cnblogs.com/pjfmeng/p/13948535.html

以上是 spring 源码解析一(bean定义) 的全部内容, 来源链接: utcz.com/z/362355.html

回到顶部