Spring的重要特征之一是IOC(Inversion of Control),即:控制反转。IOC技术促进了松耦合。Spring提供了两种IOC容器类型:BeanFactory和ApplicationContext,在类结构上,ApplicationContext是继承自BeanFactory的。下面讲解ApplicationContext容器。 下面有很简单的一段代码可以作为Spring中Bean加载的入口:
1 2
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); context.getBean("beanName");
ClassPathXmlApplicationContext用于加载CLASSPATH下的Spring配置文件。由示例可知,context.getBean("beanName");即可获取到Bean的实例,那么必然ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");就已经完成了对所有Bean实例的加载,因此可以通过ClassPathXmlApplicationContext作为Bean加载源码入口。
publicvoidrefresh()throws BeansException, IllegalStateException { Object var1 = this.startupShutdownMonitor; synchronized(this.startupShutdownMonitor) { //Prepare this context for refreshing this.prepareRefresh(); //Tell the subclass to refresh the internal bean factory ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory(); //Prepare the bean factory for use in this context. this.prepareBeanFactory(beanFactory);
try { //Allows post-processing of the bean factory in context subclasses. this.postProcessBeanFactory(beanFactory); //Invoke factory processors registered as beans in the context this.invokeBeanFactoryPostProcessors(beanFactory); //Register bean processors that intercept bean creatio this.registerBeanPostProcessors(beanFactory); //Initialize message source for this context this.initMessageSource(); //Initialize event multicaster for this context this.initApplicationEventMulticaster(); //Initialize other special beans in specific context subclasses this.onRefresh(); //check for listener beans and register them this.registerListeners(); //Instantiate all remaining (non-lazy-init) singletons this.finishBeanFactoryInitialization(beanFactory); //Last step: publish corresponding event this.finishRefresh(); } catch (BeansException var9) { if(this.logger.isWarnEnabled()) { this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9); } //Destroy already created singletons to avoid dangling resources this.destroyBeans(); //Reset 'active' flag this.cancelRefresh(var9); throw var9; } finally { this.resetCommonCaches(); }
//Prepare this context for refreshing, setting its startup date and active flag protectedvoidprepareRefresh(){ this.startupDate = System.currentTimeMillis(); this.closed.set(false); this.active.set(true); if(this.logger.isInfoEnabled()) { this.logger.info("Refreshing " + this); }
this.initPropertySources(); this.getEnvironment().validateRequiredProperties(); this.earlyApplicationEvents = new LinkedHashSet(); }
//经过一系列的处理,程序会执行到loadBeanDefinitions()相应的重载方法。 publicintloadBeanDefinitions(EncodedResource encodedResource)throws BeanDefinitionStoreException { Assert.notNull(encodedResource, "EncodedResource must not be null"); if(this.logger.isInfoEnabled()) { this.logger.info("Loading XML bean definitions from " + encodedResource.getResource()); }