一、IOC容器创建方式
Ioc容器的创建时通过ApplicationContext接口的相关实现类进行的。
如上图所示:有三种创建IOC容器的方式。
ClassPathXmlApplicationContext:从项目的根目录下加载配置文件
FileSystemXmlApplicationContext:从磁盘中的加载配置文件
AnnotationConfigApplicationContext:当使用注解配置容器对象时使用此类进行注解读取,创建容器。
二、IOC容器创建入口
1、Java中IOC容器创建
Java中通过如下代码进行配置文件读取:
ApplicationContext context = new ClassPathXmlApplicationContext("xml路径");
创建ClassPathXmlApplicationContext对象的过程中,调用refresh方法完成容器的创建与初始化。
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
//容器的创建与初始化
refresh();
}
}
2、Web中IOC容器创建
web项目中,Spring启动是在web.xml配置监听器,如下所示:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
ContextLoaderListener类实现了Tomcat容器的ServletContextListener接口,与其他Servlet监听一样,重写了两个方法:contextInitialized()方法进行web容器初始化,contextDestroyed()方法进行容器销毁。
//初始化
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
//销毁
@Override
public void contextDestroyed(ServletContextEvent event) {
closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
初始化的过程中调用ContextLoader中的initWebApplicationContext()方法,代码如下:
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//判断ServletContext是否已经存在WebApplication,如果存在则抛出异常
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
//抛出异常...
}
Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();
try {
if (this.context == null) {
//创建WebApplicationContext