springboot 源码理解
java1234
共 6849字,需浏览 14分钟
· 2020-12-24
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
/**
* Static helper that can be used to run a {@link SpringApplication} from the
* specified sources using default settings and user supplied arguments.
* @param primarySources the primary sources to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Class>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
public SpringApplication(ResourceLoader resourceLoader, Class>... primarySources) {
// 默认为null
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
// 1. 初始化主的资源
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
// 2. 推断应用类型
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 3. 初始化所有实现 ApplicationContextInitializer的子类
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 4. 初始化所有的实现ApplicationListener 的监听器,过程和3中的逻辑是一样的
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
// 5. 获取mian方法 (这块的思路比较好,以下会有介绍)
this.mainApplicationClass = deduceMainApplicationClass();
}
private
Collection getSpringFactoriesInstances(Class type) {
return getSpringFactoriesInstances(type, new Class>[] {});
}
privateCollection getSpringFactoriesInstances(Class type, Class>[] parameterTypes, Object... args) {
// 获取类加载器
ClassLoader classLoader = getClassLoader();
// Use names and ensure unique to protect against duplicates
// 获取工程名称
Setnames = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
// 创建bena工厂实例
Listinstances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
// 排序
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
public static List
loadFactoryNames(Class> factoryType, @Nullable ClassLoader classLoader) {
String factoryTypeName = factoryType.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}
private static Map> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMapresult = cache.get(classLoader);
if (result != null) {
return result;
}
try {
// FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
// 获取加载路径
Enumerationurls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry, ?> entry : properties.entrySet()) {
String factoryTypeName = ((String) entry.getKey()).trim();
for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
result.add(factoryTypeName, factoryImplementationName.trim());
}
}
}
cache.put(classLoader, result);
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
private Class> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
public ConfigurableApplicationContext run(String... args) {
// 计时器,相当于System.currentTimeMillis()获取时间进行相减来获取方法的耗时时间
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
CollectionexceptionReporters = new ArrayList<>();
// 设置环境及没有鼠标,键盘这样的硬件信息
configureHeadlessProperty();
// 获取监听器
SpringApplicationRunListeners listeners = getRunListeners(args);
// 监听器开启,进行广播时间
listeners.starting();
try {
// 获取默认的应用参数
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 加载系统配置及用户自定义配置
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
// 设置忽略的bean信息
configureIgnoreBeanInfo(environment);
// 打印banner,
Banner printedBanner = printBanner(environment);
// 创建IOC容器
context = createApplicationContext();
// 加载异常的类型信息,和构造方法中的是相同的套路
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
// IOC容器前置处理
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 刷新容器
refreshContext(context);
// IOC容器后置处理
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;
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/dangyongkang/article/details/111031858
粉丝福利:Java从入门到入土学习路线图
???
?长按上方微信二维码 2 秒
感谢点赞支持下哈
评论
微软开源MS-DOS操作系统源码,冲到GitHub第一了!
大家好,我是轩辕。这两天逛GitHub的时候,突然发现一个叫 MS-DOS的项目冲到Trending榜首了!定睛一看,微软官方啊,搜了一下才知道,原来前两天,微软把MS-DOS 4.0系统开源了!关于这个系统,估计现在很多程序员都不知道了,或者只在古老的教科书上看过这玩意儿。MS-DOS,全称为Mi
编程技术宇宙
6
架构应该如何来理解?
来源:zhuanlan.zhihu.com/p/141027477👉 欢迎加入小哈的星球 ,你将获得: 专属的项目实战 / Java 学习路线 / 一对一提问 / 学习打卡 / 赠书福利全栈前后端分离博客项目 2.0 版本完结啦, 演示链接:htt
小哈学Java
0
SpringBoot 实现图片防盗链功能
程序员的成长之路互联网/程序员/技术/资料共享 关注阅读本文大概需要 4 分钟。来自:blog.csdn.net/weixin_46157208/article/details/138051737前言出于安全考虑,我们需要后端返回的图片只允许在某个网站内展示,不想被爬虫拿到图片地
程序员的成长之路
0
springboot第70集:字节跳动后端三面经,一文让你走出微服务迷雾架构周刊
创建一个使用Kubernetes (K8s) 和 Jenkins 来自动化 GitLab 前端项目打包的CI/CD流水线,需要配置多个组件。下面,我将概述一个基本的设置步骤和示例脚本,以帮助你理解如何使用这些工具整合一个自动化流程。前提条件确保你已经有:Kubernetes 集群:用于部署 Jenk
程序源代码
0
你真的理解 devDependencies 和 dependencies 的区别吗?
点击上方 前端Q,关注公众号回复加群,加入前端Q技术交流群作者:井柏然原文:https://juejin.cn/post/7135795969370619918你是否真的理解 devDependencies 和 dependencies 的区别?如果不能确切的回答、理解还停留在模糊的阶段,
前端Q
0
AI大模型之路 第三篇:从零实现词嵌入模型,加深理解!
你好,我是郭震今天我们研究「AI大模型第三篇」:词维度预测,很多读者听过词嵌入,这篇文章解答下面问题:词嵌入是什么意思?怎么做到的?原理是什么?从零实现一个专属你数据集的词嵌入我们完整从零走一遍,根基的东西要理解透,这样才能发明出更好的东西。1 skip-gram模型Skip-gram模型是一种广泛
Python与算法社区
11
从理解路由到实现一套Router(路由)
大厂技术 高级前端 Node进阶点击上方 程序员成长指北,关注公众号回复1,加入高级Node交流群平时在Vue项目中经常用到路由,但是也仅仅处于会用的层面,很多基础知识并不是真正的理解。于是就趁着十一”小长假“查阅了很多资料,总结下路由相关的知识
程序员成长指北
10
性能爆表:SpringBoot利用ThreadPoolTaskExecutor批量插入百万级数据实测!
关注我们,设为星标,每天7:40不见不散,架构路上与您共享回复架构师获取资源大家好,我是你们的朋友架构君,一个会写代码吟诗的架构师。来源:azdebug.blog.csdn.net/article/details/103697108前言具体实现细节测试结果总结前言开发目的: 提高百万级数据
Java架构师社区
0