AbstractApplicationContext的refresh()方法简要说明

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			
			prepareRefresh();//准备启动spring容器,设置容器的启动日期和活动标志

			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();//获得容器ApplicationContext的子类BeanFactory。步骤如下:如果已经有了BeanFactory就销毁它里面的单例Bean并关闭这个BeanFactory。2.创建一个新的BeanFactory。3.对这个BeanFactory进行定制(customize),如allowBeanDefinitionOverriding,allowCircularReferences。4.转载BeanDefinitions(读取配置文件,将xml转换成对应得BeanDefinition)。5.检查是否同时启动了两个BeanFactory。

			prepareBeanFactory(beanFactory);//配置BeanFactory(就是将ApplicationContext的一些属性配置到BeanFactory上吧)。这里做了很多事情,可以看看其源码,比较重要的如设置classLoader;将BeanPostProcess注册到BeanFactory里。

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				
				invokeBeanFactoryPostProcessors(beanFactory);//触发BeanFactoryPostProcessors

				
				registerBeanPostProcessors(beanFactory);//触发BeanPostProcessors

				// 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();

				
				finishBeanFactoryInitialization(beanFactory);//初始化单例的Bean,并将其保存起来。

				// 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;
			}
		}
	}

 

`org.springframework.context.support.AbstractApplicationContext` 类中的 `refresh()` 方法用于刷新应用程序上下文。 当调用 `refresh()` 方法时,它会执行一系列的操作来刷新应用程序上下文,包括加载或刷新配置文件、创建和初始化 Bean、解析依赖关系、自动装配等。 在 Spring 应用程序中,通常会有一个特定的类继承自 `AbstractApplicationContext`,并在其 `main()` 方法中调用 `refresh()` 方法来启动应用程序上下文。这个类可以是 `ClassPathXmlApplicationContext`、`AnnotationConfigApplicationContext` 或其他 Spring 提供的特定类型的应用程序上下文。 下面是一个使用 `ClassPathXmlApplicationContext` 的例子: ```java import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { // 创建并初始化应用程序上下文 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 刷新应用程序上下文 context.refresh(); // 执行其他操作... // 关闭应用程序上下文 context.close(); } } ``` 在这个例子中,我们使用 `ClassPathXmlApplicationContext` 创建了一个基于 XML 配置文件的应用程序上下文。然后,在 `main()` 方法中调用了 `refresh()` 方法来刷新应用程序上下文。之后可以执行其他操作,并在最后关闭应用程序上下文。 请注意,具体的配置和使用方式取决于你的项目结构和需求。你可以根据自己的情况选择合适的应用程序上下文类型,并在适当的时候调用 `refresh()` 方法来刷新上下文。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值