springboot 源码理解
java1234
共 6849字,需浏览 14分钟
·
2020-12-24 00:48
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
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 秒
感谢点赞支持下哈
评论