一、什么是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方法。