spring启动简单介绍
  • 本文源码基于spring-framework-5.3.10。
spring启动的时候做了什么事情
  • 构造一个BeanFactory对象。
  • 解析配置类,得到BeanDefinition,并注册到BeanFactory中。解析@ComponentScan,此时就会完成扫描、解析@Import、解析@Bean…
  • 因为ApplicationContext还支持国际化,所以还需要初始化MessageSource对象
  • 因为ApplicationContext还支持事件机制,所以还需要初始化ApplicationEventMulticaster对象
  • 把用户定义的ApplicationListener对象添加到ApplicationContext中,等Spring启动完了就要发布事件了
  • 创建非懒加载的单例Bean对象,并存在BeanFactory的单例池中。
  • 调用LifecycleBean的start()方法
  • 发布ContextRefreshedEvent事件
源码分析
/**
 * 我们在使用AnnotationConfigApplicationContext进行创建容器的时候,
 * 他有个父类GenericApplicationContext,
 * 在他的父类默认构造方法中会进行初始化beanFactory。
 */
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
	// 构造DefaultListableBeanFactory、AnnotatedBeanDefinitionReader、ClassPathBeanDefinitionScanner
	this();
	// 配置类变为BeanDefinition
	register(componentClasses);
	refresh();
}
类在加载的时候,先调用他的父类:构造BeanFactory对象。
/**
 * 调用他的父类的构造方法
 */
public GenericApplicationContext() {
	this.beanFactory = new DefaultListableBeanFactory();
}

/**
 * DefaultListableBeanFactory的构造方法,直接调用他父类的构造方法
 */
public DefaultListableBeanFactory() {
	super();
}

/**
 * DefaultListableBeanFactory的父类的构造方法
 */
public AbstractAutowireCapableBeanFactory() {
	// 调用其父类的实现,不过他的父类什么也没干
	super();
	// 如果一个属性对应的set方法在ignoredDependencyInterfaces接口中被定义了,则该属性不会进行自动注入(是Spring中的自动注入,不是@Autowired)
	ignoreDependencyInterface(BeanNameAware.class);
	ignoreDependencyInterface(BeanFactoryAware.class);
	ignoreDependencyInterface(BeanClassLoaderAware.class);
	// 本地检测,与JVM配置有关,默认为false
	if (NativeDetector.inNativeImage()) {
		// 使用jdk的动态代理方式去生成实例策略
		this.instantiationStrategy = new SimpleInstantiationStrategy();
	}
	else {
		// 使用Cglib的动态代理方式去生成实例策略
		this.instantiationStrategy = new CglibSubclassingInstantiationStrategy();
	}
}
源码分析之无参构造做了什么
/**
 * 无参构造
 */
public AnnotationConfigApplicationContext() {
	// 一个时间记录的工机具
	StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");

	// 定义一个读取器,可以吧一个对象变为一个Bean:调用this.reader.register方法,生成BeanDefinition放入BeanDefinitionMap
	// 同时在构造reader的时候也会构造一个Environment(环境变量,配置文件信息)对象
	this.reader = new AnnotatedBeanDefinitionReader(this);
	createAnnotatedBeanDefReader.end();
	// 构造一下扫描器,有什么样子的标志需要被什么扫描
	this.scanner = new ClassPathBeanDefinitionScanner(this);
}
构造AnnotatedBeanDefinitionReader源码分析
/**
 * AnnotatedBeanDefinitionReader的构造方法
 */
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;
	// 用来解析@Conditional注解的
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
	// 注册
	AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}

/**
 * 注册的具体内容
 */
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
		BeanDefinitionRegistry registry, @Nullable Object source) {

	DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
	if (beanFactory != null) {

		// 设置beanFactory的OrderComparator为AnnotationAwareOrderComparator
		// 它是一个Comparator,是一个比较器,可以用来进行排序,比如new ArrayList<>().sort(Comparator);
		if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
			beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
		}
		// 用来判断某个Bean能不能用来进行依赖注入
		if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
			beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
		}
	}

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

	// 注册ConfigurationClassPostProcessor类型的BeanDefinition
	if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
		// 这里是注册BeanFactoryPostProcessor,用来解析配置类
		RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
		def.setSource(source);
		beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
	}

	// 注册AutowiredAnnotationBeanPostProcessor类型的BeanDefinition,主要用来除了@Autowired注解,这里只放入了BeanDefinitionMap中
	if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
		RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
		def.setSource(source);
		beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	}

	// 注册CommonAnnotationBeanPostProcessor类型的BeanDefinition,主要用来除了@Resource注解,这里只放入了BeanDefinitionMap中
	// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
	if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
		RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
		def.setSource(source);
		beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
	}

	// 注册PersistenceAnnotationBeanPostProcessor类型的BeanDefinition
	// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
	if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
		RootBeanDefinition def = new RootBeanDefinition();
		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));
	}

	// 注册EventListenerMethodProcessor类型的BeanDefinition,用来处理@EventListener注解的
	if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
		RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
		def.setSource(source);
		beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
	}

	// 注册DefaultEventListenerFactory类型的BeanDefinition,用来处理@EventListener注解的
	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;
}
构造ClassPathBeanDefinitionScanner源码分析
/**
 * ClassPathBeanDefinitionScanner的构造方法
 */ 
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
		Environment environment, @Nullable ResourceLoader resourceLoader) {

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

	// 设置一些默认的扫描
	if (useDefaultFilters) {
		registerDefaultFilters();
	}
	// 设置环境变量
	setEnvironment(environment);
	// 设置源读取器
	setResourceLoader(resourceLoader);
}

/**
 * ClassPathBeanDefinitionScanner的默认扫描的类
 */ 
protected void registerDefaultFilters() {

	// 注册@Component对应的AnnotationTypeFilter。默认扫描加了@Component注解的类,把他当做Bean
	this.includeFilters.add(new AnnotationTypeFilter(Component.class));

	ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();

	try {
		this.includeFilters.add(new AnnotationTypeFilter(
				((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
		logger.trace("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
	}
	catch (ClassNotFoundException ex) {
		// JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.
	}

	try {
		this.includeFilters.add(new AnnotationTypeFilter(
				((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
		logger.trace("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
	}
	catch (ClassNotFoundException ex) {
		// JSR-330 API not available - simply skip.
	}
}
构造的第二行register(componentClasses);配置类变为BeanDefinition
public void register(Class<?>... componentClasses) {
	// 校验
	Assert.notEmpty(componentClasses, "At least one component class must be specified");
	// 日期记录
	StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register")
			.tag("classes", () -> Arrays.toString(componentClasses));
	// 注册到BeanDefinitionMap中
	this.reader.register(componentClasses);
	registerComponentClass.end();
}
构造的第三行refresh();源码分析
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

		// Prepare this context for refreshing.
		// 准备刷新的操作
		// 设置一些标记、检查必要的key
		prepareRefresh();

		// Tell the subclass to refresh the internal bean factory.
		// 这里会判断能否刷新,并且返回一个BeanFactory, 刷新不代表完全情况,主要是先执行Bean的销毁,然后重新生成一个BeanFactory,再在接下来的步骤中重新去扫描等等。
		// 简单说,boot支持重复刷新,MVC支持
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// Prepare the bean factory for use in this context.
		// 准备BeanFactory
		// 1. 设置BeanFactory的类加载器、SpringEL表达式解析器、类型转化注册器
		// 2. 添加三个BeanPostProcessor,注意是具体的BeanPostProcessor实例对象
		// 3. 记录ignoreDependencyInterface
		// 4. 记录ResolvableDependency
		// 5. 添加三个单例Bean
		prepareBeanFactory(beanFactory);

		try {
			// Allows post-processing of the bean factory in context subclasses.
			// 模板方法模式,子类来设置一下BeanFactory。
			// MVC进行了实现,boot基本上无实现
			postProcessBeanFactory(beanFactory);

			StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");

			// Invoke factory processors registered as beans in the context.
			// BeanFactory准备好了之后,执行BeanFactoryPostProcessor,开始对BeanFactory进行处理
			// 默认情况下:
			// 此时beanFactory的beanDefinitionMap中有6个BeanDefinition,5个基础BeanDefinition+AppConfig的BeanDefinition
			// 而这6个中只有一个BeanFactoryPostProcessor:ConfigurationClassPostProcessor
			// 这里会执行ConfigurationClassPostProcessor进行@Component的扫描,扫描得到BeanDefinition,并注册到beanFactory中
			// 注意:扫描的过程中可能又会扫描出其他的BeanFactoryPostProcessor,那么这些BeanFactoryPostProcessor也得在这一步执行
			invokeBeanFactoryPostProcessors(beanFactory);  // scanner.scan()

			// Register bean processors that intercept bean creation.
			// 将扫描到的BeanPostProcessors实例化并排序,并添加到BeanFactory的beanPostProcessors属性中去
			registerBeanPostProcessors(beanFactory);

			beanPostProcess.end();

			// Initialize message source for this context.
			// 国际化处理:设置ApplicationContext的MessageSource,要么是用户设置的,要么是DelegatingMessageSource
			initMessageSource();

			// Initialize event multicaster for this context.
			// 事件发布器处理:设置ApplicationContext的applicationEventMulticaster,么是用户设置的,要么是SimpleApplicationEventMulticaster
			initApplicationEventMulticaster();

			// Initialize other special beans in specific context subclasses.
			// 给子类的模板方法
			onRefresh();

			// Check for listener beans and register them.
			// 事件监听器处理:把定义的ApplicationListener的Bean对象,设置到ApplicationContext中去,并执行在此之前所发布的事件
			registerListeners();

			// Instantiate all remaining (non-lazy-init) singletons.
			// 加载非懒加载的单例Bean
			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();
			contextRefresh.end();
		}
	}
}
准备刷新prepareRefresh源码分析
protected void prepareRefresh() {
	// Switch to active.
	// 设置一些标记,开始工作
	this.startupDate = System.currentTimeMillis();
	this.closed.set(false);
	this.active.set(true);

	// 打印日志
	if (logger.isDebugEnabled()) {
		if (logger.isTraceEnabled()) {
			logger.trace("Refreshing " + this);
		}
		else {
			logger.debug("Refreshing " + getDisplayName());
		}
	}

	// Initialize any placeholder property sources in the context environment.
	// 模板方法模式,用于子类重写。比如子类可以把ServletContext中的参数对设置到Environment
	initPropertySources();

	// Validate that all properties marked as required are resolvable:
	// see ConfigurablePropertyResolver#setRequiredProperties
	// 验证Environment有没有必须的key。通过Environment.setRequiredProperties("zhangwei")进行设置
	getEnvironment().validateRequiredProperties();

	// Store pre-refresh ApplicationListeners...
	// 监听器相关
	if (this.earlyApplicationListeners == null) {
		this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
	}
	else {
		// Reset local application listeners to pre-refresh state.
		this.applicationListeners.clear();
		this.applicationListeners.addAll(this.earlyApplicationListeners);
	}

	// Allow for the collection of early ApplicationEvents,
	// to be published once the multicaster is available...
	this.earlyApplicationEvents = new LinkedHashSet<>();
}
准备BeanFactory源码分析
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	// 设置BeanFactory的类加载器
	beanFactory.setBeanClassLoader(getClassLoader());

	// Spring5.3中新增的配置功能,可以选择是否开启Spel功能(EL表达式),shouldIgnoreSpel默认为false,表示开启。
	if (!shouldIgnoreSpel) {
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	}

	// 添加一个ResourceEditorRegistrar,注册一些级别的类型转化器
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// Configure the bean factory with context callbacks.
	// 组成一个BeanPostProcessor,用来处理EnvironmentAware、EmbeddedValueResolverAware等回调
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

	// 如果一个属性对应的set方法在ignoredDependencyInterfaces接口中被定义了,则该属性不会进行自动注入(是Spring中的自动注入,不是@Autowired)
	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
	beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);

	// BeanFactory interface not registered as resolvable type in a plain factory.
	// MessageSource registered (and found for autowiring) as a bean.
	// 指定一下Bean类型对应的具体Bean是什么
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// Register early post-processor for detecting inner beans as ApplicationListeners.
	// ApplicationListenerDetector负责把ApplicantsListener类型的Bean注册到ApplicationContext中
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	// Aspectj本身是通过编译期进行代理的,在Spring中就跟LoadTimeWeaver有关
	if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// Set a temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	// Register default environment beans.
	// environment内部的几个类的具体Bean注册
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
	// 监控的Bean进行注册
	if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
		beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
	}
}
最终的刷新方法:finishRefresh源码分析
protected void finishRefresh() {
	// Clear context-level resource caches (such as ASM metadata from scanning).
	// 清空和ASM相关的信息
	clearResourceCaches();

	// Initialize lifecycle processor for this context.
	// 监听spring容器的什么周期:设置lifecycleProcessor,默认为DefaultLifecycleProcessor
	initLifecycleProcessor();

	// Propagate refresh to lifecycle processor first.
	// 调用LifecycleBean的start()
	getLifecycleProcessor().onRefresh();

	// Publish the final event.
	// 发布事件的监听器去监听这个事件
	publishEvent(new ContextRefreshedEvent(this));

	// Participate in LiveBeansView MBean, if active.
	if (!NativeDetector.inNativeImage()) {
		LiveBeansView.registerApplicationContext(this);
	}
}

结束语
  • 获取更多本文的前置知识文章,以及新的有价值的文章,让我们一起成为架构师!
  • 关注公众号,可以让你对MySQL、并发编程、spring源码有深入的了解!
  • 关注公众号,后续持续高效的学习JVM!
  • 这个公众号,无广告!!!每日更新!!!
    【spring】spring启动的整体思路_java