Spring生态源码解读(一)
文章目录
SpringBoot源码解读(一)
SpringApplication的实例化
Springboot版本:2.2.10.RELEASE
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
public SpringApplication(Class<?>... primarySources) {
this(null, primarySources);
}
/**
* Create a new {@link SpringApplication} instance. The application context will load
* beans from the specified primary sources (see {@link SpringApplication class-level}
* documentation for details. The instance can be customized before calling
* {@link #run(String...)}.
* @param resourceLoader the resource loader to use
* @param primarySources the primary bean sources
* @see #run(Class, String[])
* @see #setSources(Set)
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
//资源初始化加载器 初始化
this.resourceLoader = resourceLoader;
//断言主要的资源加载类不能为空
Assert.notNull(primarySources, "PrimarySources must not be null");
//资源类去重
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//推断web类型
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//向SpringApplication注册系统初始化器
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
//向SpringApplication注册系统监听器
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//推断应用类型为main
this.mainApplicationClass = deduceMainApplicationClass();
}从上述代码不难发现springboot启动的步骤是先实例化了SpringApplication之后在调用其实例化的对象的run方法来完成整个程序的启动;
首先我们先聊聊SpringApplication的实例化过程,看看它是如何完成实例化的,而实例化的过程中又做了什么操作。
SpringApplication实例化主要完成了对web容器的推断,对系统初始化器和监控器属性的赋值;
private static final String WEBFLUX_INDICATOR_CLASS = "org.springframework.web.reactive.DispatcherHandler";
private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer";
private static final String SERVLET_APPLICATION_CONTEXT_CLASS = "org.springframework.web.context.WebApplicationContext";
private static final String REACTIVE_APPLICATION_CONTEXT_CLASS = "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext";
static WebApplicationType deduceFromClasspath() {
if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : SERVLET_INDICATOR_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
return WebApplicationType.SERVLET;
}首先聊聊SpringApplication推断web容器类型的过程,先从静态方法deduceFromClasspath方法开始看,发现该方法主要是调用ClassUtils的isPresent(String className, ClassLoader classLoader)
方法对SpringApplication定义的一些成员变量值(className)判断然后得到不同的web容器类型的推断结果,而isPresent方法主要是判断传入的className是否可被对应的classLoader通过反射的方式加载到,如果可以就返回true,否则抛出异常(当然异常被try{}catch()捕获了)返回false,代码实现如下:
public static boolean isPresent(String className, @Nullable ClassLoader classLoader) {
try {
forName(className, classLoader);
return true;
}
catch (IllegalAccessError err) {
throw new IllegalStateException("Readability mismatch in inheritance hierarchy of class [" +
className + "]: " + err.getMessage(), err);
}
catch (Throwable ex) {
// Typically ClassNotFoundException or NoClassDefFoundError...
return false;
}
}通过classUtils的isPresent对SpringApplication的多个成员变量值判定,确认SpringApplication的web容器类型。
其次我们再来看看系统初始化器的注册过程,系统初始化器属性的赋值由SpringApplication的getSpringFactoriesinstances(Class<T> type, Class<?>[] parameterTypes, Object... args)实现,主要分为两个步骤:
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
return getSpringFactoriesInstances(type, new Class<?>[] {});
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = getClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
其一实例化类加载器AppClassLoader,然后通过SpringFactoriesLoaders的loadFactoryNames方法获取需要实例化的系统初始化器的类名;
具体实现如下:
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
String factoryTypeName = factoryType.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
Enumeration<URL> urls = (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);
}
}
该方法先从缓存中获取系统初始化器名称,如果缓存中有就直接返回;不为空的话就判断classLoader是否为空,因为之前实例化了一个AppClassLoader,所以调用该classLoader对象的getResources(String FACTORIES_RESOURCE_LOCATION)方法获取所引入jar包的web/spring.factories下的资源,然后遍历该资源,将该资源转化为properties集合(该property对象是key,value的形式),之后存入到一个map集合中,其中key是类名,value则是properties里面的value值(可能是集合,如果是集合就通过逗号分割);加载到spring.factories的资源后,在通过getOrDefault方法通过key,也就是系统初始化器的名称获取对应的value集合;
其二:通过反射获取到构造器,实例化之前获取到的系统初始化器的集合;
@SuppressWarnings("unchecked")
private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes,
ClassLoader classLoader, Object[] args, Set<String> names) {
List<T> instances = new ArrayList<>(names.size());
for (String name : names) {
try {
Class<?> instanceClass = ClassUtils.forName(name, classLoader);
Assert.isAssignable(type, instanceClass);
Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
T instance = (T) BeanUtils.instantiateClass(constructor, args);
instances.add(instance);
}
catch (Throwable ex) {
throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
}
}
return instances;
}
如上所示,appClassLoader通过名称加载到类,然后根据类和传入的参数通过反射获取到构造器,再通过构造一个新的对象实例化该类,最后加入到系统初始化器的列表中去,然后将集合赋值给SpringApplication的系统初始化器的属性,注册到SpringApplication中;
系统监听器的实例化和赋值过程与系统初始化器如出一辙,这里就不做过多赘述,最后奉上宝图一张

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论