springboot一般通过以下main方法来启动项目

@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

查看源码发现加载的主要逻辑写在了

具体逻辑如下:
/**
* Run the Spring application, creating and refreshing a new
* {@link ApplicationContext}.
* @param args the application arguments (usually passed from a Java main method)
* @return a running {@link ApplicationContext}
*/
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
//1.创建容器
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
//2.把bean装载进容器context中去
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);

refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
} try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}

下面重点讲"把bean装载进容器context中去"的这个方法prepareContext(context, environment, listeners, applicationArguments, printedBanner)的逻辑

方法的代码实现逻辑如下:

private void prepareContext(ConfigurableApplicationContext context,
ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments, Banner printedBanner) {
context.setEnvironment(environment);
postProcessApplicationContext(context);
applyInitializers(context);
listeners.contextPrepared(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// Add boot specific singleton beans
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
// Load the sources 也就要加载的声明配置的类,这里是声明了@SpringBootApplication的DemoApplication
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
//把声明了@SpringBootApplication的类加载进容器的具体实现
load(context, sources.toArray(new Object[0]));
listeners.contextLoaded(context);
}

load方法的具体实现:

/**
* Load beans into the application context.
* @param context the context to load beans into
* @param sources the sources to load
*/
protected void load(ApplicationContext context, Object[] sources) {
if (logger.isDebugEnabled()) {
logger.debug(
"Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
}
//这个BeanDefinationLoader的实现类为org.springframework.boot.BeanDefinitionLoader,为springboot自定义的一个beanDefination的加载器,专门用来加载配置声明的类的
        BeanDefinitionLoader loader = createBeanDefinitionLoader(
getBeanDefinitionRegistry(context), sources);
if (this.beanNameGenerator != null) {
loader.setBeanNameGenerator(this.beanNameGenerator);
}
if (this.resourceLoader != null) {
loader.setResourceLoader(this.resourceLoader);
}
if (this.environment != null) {
loader.setEnvironment(this.environment);
}
//
org.springframework.boot.BeanDefinitionLoader把beanDefination加载进spring的BeanDefinationRegistry中的方法
     loader.load();

 }

以下为org.springframework.boot.BeanDefinitionLoader的loan方法实现逻辑:

private int load(Class<?> source) {
if (isGroovyPresent()
&& GroovyBeanDefinitionSource.class.isAssignableFrom(source)) {
// Any GroovyLoaders added in beans{} DSL can contribute beans here
GroovyBeanDefinitionSource loader = BeanUtils.instantiateClass(source,
GroovyBeanDefinitionSource.class);
load(loader);
}
if (isComponent(source)) {
//通过org.springframework.context.annotation.AnnotatedBeanDefinitionReader.AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry)来注册注解扫描的类定义
        this.annotatedReader.register(source);
return 1;
}
return 0;
}
org.springframework.context.annotation.AnnotatedBeanDefinitionReader的作用是啥呢?来看看
AnnotatedBeanDefinitionReader类的注释:
/**
* Convenient adapter for programmatic registration of annotated bean classes.
* This is an alternative to {@link ClassPathBeanDefinitionScanner}, applying
* the same resolution of annotations but for explicitly registered classes only.
*
* @author Juergen Hoeller
* @author Chris Beams
* @author Sam Brannen
* @author Phillip Webb
* @since 3.0
* @see AnnotationConfigApplicationContext#register
*/
public class AnnotatedBeanDefinitionReader

意思就是:

用于声明bean类的编程注册的方便的适配器,
这是ClassPathBeanDefinitionsCanner的替代方法,应用
声明类解析,但仅限于显式注册的类。

springboot加载bean过程探索的更多相关文章

  1. spring加载Bean的解析过程(二)

    1.例如: BeanFactory bf = new XmlBeanFactory(new ClassPathResource("spring.xml")); User user ...

  2. spring加载bean流程解析

    spring作为目前我们开发的基础框架,每天的开发工作基本和他形影不离,作为管理bean的最经典.优秀的框架,它的复杂程度往往令人望而却步.不过作为朝夕相处的框架,我们必须得明白一个问题就是sprin ...

  3. IoC 之加载 Bean:总结

    上文中我们将bean已经加载到了IOC容器中,接下来我们将把IOC加载Bean出来进行代码解析 备注:(有些解释是参考别个博客的相关解释 )一起探讨请加我QQ:1051980588 bean 的初始化 ...

  4. Spring多种加载Bean方式简析

    1 定义bean的方式 常见的定义Bean的方式有: 通过xml的方式,例如: <bean id="dictionaryRelMap" class="java.ut ...

  5. 【死磕 Spring】----- IOC 之 加载 Bean

    原文出自:http://cmsblogs.com 先看一段熟悉的代码: ClassPathResource resource = new ClassPathResource("bean.xm ...

  6. sping加载bean都发生了些什么

    问题描述:使用@Autowired注入的类,没有实例化 //Controller @RequestMapping(value="/deepblue") @Controller pu ...

  7. spring Boot加载bean

    1.SpringBoot中加载bean,可以使用注解@compenent直接加载到applicationContext容器中 2.在直接类@Configuration中,手动注册bean,如:

  8. log4j的学习和log4j在程序中使用的加载作用过程

    昨天进行代码评审的时候,大家都纠结在了日志信息应该如何输出上,其实我想大家应该一直都在使用log4j来对日志信息进行输出,但是未想应该有很大一部分人对log4j是不了解的,我遇到这个问题的时候也到网上 ...

  9. Springboot 加载配置文件源码分析

    Springboot 加载配置文件源码分析 本文的分析是基于springboot 2.2.0.RELEASE. 本篇文章的相关源码位置:https://github.com/wbo112/blogde ...

随机推荐

  1. jquery.validate.js表单验证 jquery.validate.js的用法

    jquery.validate.js这个插件已经用了2年多了,是一个不可多得的表单验证最方便快捷的插件.基于jquery的小插件,基本小白一学就会上手,对于项目表单页面比较多,元素比较多的校验,该插件 ...

  2. vue-过滤器-时间戳转换

    main.js // 将时间戳转日期格式的过滤器 Vue.filter('dateFormat', (dataStr) => { var time = new Date(dataStr); fu ...

  3. javascript框架(库)

    javascript框架(库)高级JavaScript编程,尤其是复杂的浏览器差异处理,通常是困难和耗时的.为了响应这些调整,出现了许多javascript(helper)库.这些JavaScript ...

  4. Win10 OpenCV3.3.0+VS2013配置大坑,OpenCV解决方案编译报错“找不到python36_d.lib”错误

    今天因为想要用OpenCV做图像识别,小白一个,在网上找到一个教程,但是需要配置OpenCV3.3.0的环境,于是又在网上找OpenCV3.3.0+VS2013(因为我之前已经安过了VS2013),前 ...

  5. PXE help Tips

    http://www.kano.org.uk/projects/pxe/ http://howto.basjes.nl/linux/installing-fedora-linux-via-pxe-x8 ...

  6. 记录旧手机(米6)安装Linux(Ubuntu16.04)踩过的坑

    旧的小米6在抽屉吃灰半年,一直没想好要怎么处理,于是就想着安装Linux. 完整教程来自https://blog.csdn.net/Greepex/article/details/85333027 原 ...

  7. mysql数据库: 用户管理、pymysql使用、navicat插件使用

    一.用户管理 二.pymysql增删改查 三.sql注入攻击 一.用户管理 数据安全非常重要 不可能随便分配root账户 应该按照不同开发岗位分配不同的账户和权限 mysql中 将于用户相关的数据放在 ...

  8. C++实例 分解质因数

    分解质因数: 每个合数都可以写成几个质数相乘的形式.其中每个质数都是这个合数的因数,叫做这个合数的分解质因数.分解质因数只针对合数. 分解质因数的算式叫短除法.求一个数分解质因数,要从最小的质数除起, ...

  9. 使用Task的Wait和Result时注意

    如果计算限制的任务抛出未处理的异常,该异常会被“吞噬”并存储到一个集合中,而线程池线程可以返回到线程池中.调用Wait方法或者Result属性时,这些成员会抛出一个System.AggregateEx ...

  10. CNN for NLP

    卷积神经网络在自然语言处理任务中的应用.参考链接:Understanding Convolutional Neural Networks for NLP(2015.11) Instead of ima ...