一、什麼是ioc容器
IoC容器指的Spring中BeanFactory,底層使用Map存儲了通過反射生成的Bean實例。
二、ioc核心組件
1、BeanFactory:Spring創建Bean對象的工廠接口,定義了IOC容器的基本功能規範。其體系結構如下圖所示(來源:https://blog.csdn.net/yujin753/article/details/47043143):
2、ApplicationContext:Spring最常用的接口,繼承BeanFactory ,在BeanFactory IOC容器的基礎上添加了許多對高級容器的支持,我們一般使用這個。其體系結構如下圖所示(來源:https://blog.csdn.net/yujin753/article/details/47043143):
3、BeanDefinition:用來描述Spring中Bean對象。BeanFactory可根據 BeanDefinition 的描述進行 bean 的創建和管理。其體系結構如下圖所示(來源:https://blog.csdn.net/yujin753/article/details/47043143):
- 以下爲常用組件總的關係圖(來源:http://singleant.iteye.com/blog/1177358)
三、源碼入口
這裏介紹兩種進入源碼入口的方法
第一種方式:
ApplicationContext context = new ClassPathXmlApplicationContext(“spring.xml”);
context.getBean(XXX.class);
分析以上代碼,第2行能夠獲取到bean對象,說明第1行已經完成了所有bean的加載,所以ClassPathXmlApplicationContext可以當做入口。
進入ClassPathXmlApplicationContext,依次調用重載的構造方法,進入以下代碼,代碼中refresh()爲初始化spring容器的核心方法。
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
//核心代碼
refresh();
}
}
第二種方式:
1、web容器啓動之後加載web.xml,此時加載ContextLoaderListener監聽器。
<!--通過ContextLoaderListener監聽啓動spring容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
2、進入ContextLoaderListener類的contextInitializd方法,創建Web環境中的Spring上下文對象。
//ServletContext域對象創建的時候觸發該方法
@Override
public void contextInitialized(ServletContextEvent event) {
//初始化web環境中的spring容器
initWebApplicationContext(event.getServletContext());
}
3、進入ContextLoader類的initWebApplicationContext方法。
if (this.context == null) {
//創建上下文
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent ->
// determine parent for root web application context, if any.
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
//初始化單例bean對象
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
這裏主要分析兩個方法(createWebApplicationContext和configureAndRefreshWebApplicationContext)
(1)進入第3行的createWebApplicationContext方法,該方法是創建上下文的方法。
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
Class<?> contextClass = determineContextClass(sc);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
進入determineContextClass方法, 這個方法是用來確定上下文的實現類。
protected Class<?> determineContextClass(ServletContext servletContext) {
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
else {
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}
分析這段代碼:
- 首先讀取web.xml中配置的contextClass值,若爲空,取默認策略屬性的class(XmlWebApplicationContext)。
- 看下默認配置的加載及配置信息,默認策略對象爲defaultStrategies。從以下代碼可以看出,加載了在當前類同級目錄中的ContextLoader.properties文件。這裏可以看出,createWebApplicationContext方法返回的接口ConfigurableWebApplicationContext,其實返回的是它的實現類XmlWebApplicationContext。
private static final Properties defaultStrategies;
static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized
// by application developers.
try {
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
}
}
ContextLoader.properties代碼內容:
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
(2)進入第17行的configureAndRefreshWebApplicationContext方法,該方法中最終也是調用初始化Bean的refresh方法。
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
//核心代碼
wac.refresh();
}
看上面第32行代碼,因爲wac本質是XmlWebApplicationContext類,XmlWebApplicationContext繼承了AbstractApplicationContext抽象類(該類實現了refresh方法),繼承關係如下圖所示,因此這裏其實是調用了AbstractApplicationContext類的refresh方法。
總結:以上可以看出,入口的兩種方式都是通過調用AbstractApplicationContext類中的refresh()方法初始化spring容器的。接下來將在下一篇重點分析該refresh方法。