转载:https://blog.csdn.net/u010644448/article/details/59108799,
https://www.cnblogs.com/xrq730/p/6285358.html
ApplicationContext ac = new ClassPathXmlApplicationContext(“spring.xml”);
ac.getBean(XXX.class);
ClassPathXmlApplicationContext的构造函数:
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
调用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.
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);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory)
(这里注意,BeanPostProcessor接口针对的是每个Bean初始化前后做的操作,在nvokeBeanFactoryPostProcessors(beanFactory)方法里,而BeanFactoryPostProcessor接口针对的是所有Bean实例化前的操作,在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.
destroyBeans();
// Reset ‘active’ flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
}
}
obtainFreshBeanFactory()这个方法创建BeanFactory
另外,在关键的doGerBean方法里有一段是用来告诉我们如果一个BEAN依赖另一个的化,是会先去加载被依赖的Bean的
我们经常在bean标签中看到depends-on这个属性,就是通过这段保证了depends-on依赖的Bean会优先于当前Bean被加载