再读Spring源码-Spring的启动和加载

256 阅读2分钟

Spring的启动就是IoC容器的启动过程。IoC容器的启动在Spring源码中就是ApplicationContext的初始化。ApplicationContext的初始化有多种方式。

比如在main方法中new一个对象,初始化ApplicationContext,启动IoC容器。

public static void main(String[] args) {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		//启动IoC容器
		ctx.refresh();
		
		ctx.getBean("sample");
	}

还有一种就是我们常用的WebApplicationContext的初始化。这种方法是通过Servlet容器解析web.xml,获取listener标签节点的值,通过反射生成对象,listener里的类是ServletContextListener接口的实现,然后调用contextInitialized方法初始化,启动IoC容器

public interface ServletContextListener extends EventListener {

    public void contextInitialized(ServletContextEvent sce);

    public void contextDestroyed(ServletContextEvent sce);
}
<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"  
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name>oa</display-name>
 
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
 
</web-app>

有人可能就好奇了,在SpringBoot里没有web.xml,那这个IoC容器是怎么启动的呢?下面我们来分析分析。 SpringBoot启动IoC容器的入口是在SpringApplication.run方法里。SpringBoot没有xml配置,而是通过注解和配置文件来实现的。

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);
			//创建applicationContext
			context = createApplicationContext();
			exceptionReporters = getSpringFactoriesInstances(
					SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
			prepareContext(context, environment, listeners, applicationArguments,
					printedBanner);
			//这里refresh初始化IoC容器并开始加载依赖
			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, listeners, exceptionReporters, ex);
			throw new IllegalStateException(ex);
		}
		listeners.running(context);
		return context;
	}

这里只是简单的展示了一下Spring中IoC容器是在何时何地启动的。找到入口后大家就可以通过入口进入断点跟踪,一步一步的了解容器启动前环境的准备,启动时Bean的载入等都是如何实现的了。