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的載入等都是如何實現的了。