IOC容器的创建

一、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
				
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值