`
eils2000
  • 浏览: 50368 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

New ClassPathXmlApplicationContext经历了哪些事情

阅读更多
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:NonOsgiConsumerSample.xml");

 这是一段很简单的ApplicationContext初始化的代码,但是在这段代码的背后,springframework又为我们做了哪些事情,使得我们能够从容器中方便的获取我们想要的bean?

跟踪代码我们发现在创建一个ClassPathXmlApplicationContext的过程中,它主要经历了以下几个步骤

ClassPathXmlApplicationContext(String configLocation) ----> 
ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) ----->
AbstractXmlApplicationContext(ApplicationContext parent) ---->
AbstractRefreshableConfigApplicationContext(ApplicationContext parent)---->
AbstractRefreshableApplicationContext(ApplicationContext parent) ->
AbstractApplicationContext(ApplicationContext parent)
//最终在AbstractApplicationContext.refresh()完成bean初始化
AbstractApplicationContext.refresh()

AbstractXmlApplicationContext实现了loadBeanDefinitions() ,它的子类只需实现getConfigResources()

 

	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
		beanDefinitionReader.setResourceLoader(this);
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

		// Allow a subclass to provide custom initialization of the reader,
		// then proceed with actually loading the bean definitions.
		initBeanDefinitionReader(beanDefinitionReader);
		loadBeanDefinitions(beanDefinitionReader);
	}

 AbstractRefreshableApplicationContext支持多重刷新,每次在内部会创建一个新的bean factory实例,子类只需实现loadBeanDefinitions()

//AbstractRefreshableApplicationContext关键代码	
protected final void refreshBeanFactory() throws BeansException {
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			customizeBeanFactory(beanFactory);
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException(
					"I/O error parsing XML document for application context [" + getDisplayName() + "]", ex);
		}
	}

 

AbstractApplicationContext.refresh()

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();    //无需关注

			// Tell the subclass to refresh the internal bean factory.调用了refreshBeanFactory()
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);   

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);  //无需关注,在webapplicationcontext可能用到

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);
                                                                //实例化和调用所有实现了BeanFactoryPostProcessor的bean
				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				// Destroy already created singletons to avoid dangling resources.
				beanFactory.destroySingletons();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}
		}
	}

 

分享到:
评论

相关推荐

    模拟spring中的ClassPathXmlApplicationContext类的实现

    例如,`new ClassPathXmlApplicationContext("beans.xml")`。 2. **读取配置文件**:在内部,`ClassPathXmlApplicationContext`使用`Resource`接口从类路径中获取XML配置文件。`Resource`对象封装了对资源的访问,...

    spring的基础(一)自己写的ClassPathXmlApplicationContext类

    在本篇博文中,我们将深入探讨Spring框架的基础知识,特别是关注如何自己编写一个`ClassPathXmlApplicationContext`类。`ClassPathXmlApplicationContext`是Spring框架中用于加载和管理配置元数据的核心类,它允许...

    spring容器的触发事件 ClassPathXmlApplicationContext的start()方法的用法

    AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring/applicationContext.xml"); ctx.start(); // ContextStartedEvent 发生 ctx.refresh(); // ContextRefreshedEvent 发生 ctx.stop...

    maven相关资料

    ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml","dao.xml"}); 或者用通配符: ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/*....

    spring为ApplicationContext提供的3种实现分别为:ClassPathXmlApplicationContext

    例如,我们通常会创建如`new ClassPathXmlApplicationContext("beans.xml")`这样的实例,其中"beans.xml"是定义bean配置的文件。它会扫描指定的类路径下所有符合的XML配置文件,并将其中的bean定义加载到上下文中。 ...

    ActiveMQ-demo

    ApplicationContext ac = new ClassPathXmlApplicationContext("spring/applicationContext-jms-producer.xml"); //获取生产者发送消息服务接口 MessageSender messageSender = (MessageSender)ac.getBean...

    spring核心

    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); (2)ApplicationContext context = new FileSystemXmlApplicationContext ("applicationContext.xml"); 一般用第...

    dubbo的使用

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationProvider.xml" }); context.start(); System.in.read(); } } ``` 5. **服务消费**:在客户端,配置...

    spring技术入门相关源码

    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); //输出spring容器 System.out.println(ctx); //打印加载的bean名称 System.out.println(java.util.Arrays....

    spring结合mongodb例子(maven java project)

    例子简单的实现了spring结合mongo的例子 ...通过ApplicationContext applicationContext = new ClassPathXmlApplicationContext("mongo.xml");加载方式:App.java 3.列出log日志的java代码获取方式

    spring 获得applicationcontext公用方法

    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); ``` - 注解配置方式:使用`AnnotationConfigApplicationContext`,传入包含@Configuration注解的类的全限定名: ...

    处理ssh组合框架中如何用getBean获取实体

    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); MyEntity myEntity = (MyEntity) context.getBean("myEntity"); ``` 2. **SSH框架中的bean管理** 在SSH框架中,Spring作为IoC...

    ApplicationContext及它的3种实现

    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); // 加载多个配置文件 String[] locations = {"applicationContext.xml", "serviceContext.xml"}; ...

    Spring中如何加载多个配置文件.pdf

    ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"a1.xml", "a2.xml"}); // 接下来可以使用context对象获取Bean实例等操作 } } ``` 在这个例子中,`...

    17-IoC配置-import导入配置文件

    new classPathxmlApplicationcontext ( "config1.xml " , "config2.xml" ); Spring容器中的bean定义冲突问题 同id的bean,后定义的覆盖先定义的 导入配置文件可以理解为将导入的配置文件复制粘贴到对应位置 ...

    XFire与Spring集成WebService客户端的两种开发方式.pdf

    ApplicationContext ctx = new ClassPathXmlApplicationContext("client.xml"); HelloService helloService = (HelloService) ctx.getBean("XFireServerDemo"); ``` 在这个例子中,`HelloService`接口代表了服务方...

    spring依赖注入bean

    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); ``` **Bean 的配置** Bean 的配置通常在 XML 文件中完成,比如 `beans.xml`。在这个文件中,我们可以定义 Bean 的 ID、类名以及...

    java中获得spring中的BEAN

    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); IWorkFlowService service = (IWorkFlowService) context.getBean("serviceBeanId"); // 进行业务操作 } } ``` ...

    ApplicationContext及它的3种实现.docx

    例如,`new ClassPathXmlApplicationContext("bean.xml")`会查找类路径下的"bean.xml"文件来初始化容器。可以同时加载多个配置文件,只需将文件名放在字符串数组中传入构造函数即可。 - **...

Global site tag (gtag.js) - Google Analytics