FrameworkServlet中的wac.refresh()
如下为初始化MVC部分的操作:
java 代码 initmultipartresolver(); initlocaleresolver(); initthemeresolver(); inithandlermappings(); inithandleradapters(); inithandlerexceptionresolvers(); initviewresolver();
现在有一个疑问 initHandlerMappings(ApplicationContext context)中的ApplicationContext的实现在web中是哪一个,可以从下面得到结论
java 代码
public static final Class DEFAULT_CONTEXT_CLASS = XmlWebApplicationContext.class; private Class contextClass = DEFAULT_CONTEXT_CLASS;
可以看出这个地方是实例化的是XmlWebApplicationContext的一个实例,那么这个实例是在哪个地方被实例化的呢?在DispatchServelet的父类FrameworkServlet中可以找到如下的代码,
java 代码 WebApplicationContext parent = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); WebApplicationContext wac = createWebApplicationContext(parent);
ok,我们现在就可以用这个wac了,顺便看看这个实例里边都有什么东西:
java 代码
wac.setParent(parent);//web.xml中加载的context
wac.setServletContext(getServletContext()); wac.setServletConfig(getServletConfig()); wac.setNamespace(getNamespace()); if (getContextConfigLocation() != null) { wac.setConfigLocations( StringUtils.tokenizeToStringArray( getContextConfigLocation(), ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS)); }//比较有用
wac.addApplicationListener(this);
继续我们的MVC探索-->
下面是MVC的部分,提前分析一下
java 代码
protected List getDefaultStrategies(ApplicationContext context, Class strategyInterface) throws BeansException { String key = strategyInterface.getName();//equals org.springframework.web.servlet.HandlerMapping
List strategies = null; String value = defaultStrategies.getProperty(key); //org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping.class
if (value != null) { String[] classNames = StringUtils.commaDelimitedListToStringArray(value);//等效于split
strategies = new ArrayList(classNames.length); for (int i = 0; i < classNames.length; i++) { String className = classNames[i]; try { Class clazz = ClassUtils.forName(className, getClass().getClassLoader()); Object strategy = createDefaultStrategy(context, clazz); strategies.add(strategy); } catch (ClassNotFoundException ex) { throw new BeanInitializationException( "Could not find DispatcherServlet's default strategy class [" + className + "] for interface [" + key + "]", ex); } catch (LinkageError err) { throw new BeanInitializationException( "Error loading DispatcherServlet's default strategy class [" + className + "] for interface [" + key + "]: problem with class file or dependent class", err); } } }else { strategies = Collections.EMPTY_LIST; } return strategies; } protected Object createDefaultStrategy(ApplicationContext context, Class clazz) throws BeansException { return context.getAutowireCapableBeanFactory().createBean( clazz, AutowireCapableBeanFactory.AUTOWIRE_NO, false); //org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping.class
}
context 为XmlWebApplicationContext的一个实例,而
java 代码
public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext public abstract class AbstractRefreshableWebApplicationContext extends AbstractRefreshableApplicationContext implements ConfigurableWebApplicationContext, ThemeSource public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext, DisposableBean { public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException { return getBeanFactory(); } } 在AbstractRefreshableApplicationContext中 public final ConfigurableListableBeanFactory getBeanFactory() { synchronized (this.beanFactoryMonitor) { if (this.beanFactory == null) { throw new IllegalStateException("BeanFactory not initialized or already closed - " + "call 'refresh' before accessing beans via the ApplicationContext"); } return this.beanFactory; } }
说明这个时候BeanFactory已经初始化好了,那么在哪个地方初始化好的呢?可以想象到的地方就是XmlWebApplicationContext在new的时候会初始化这个BeanFactory?在WebApplicationContext createWebApplicationContext(WebApplicationContext parent)时候,也就是在初始化ApplicationContext的时候有如下操作
wac.refresh();
也就是初始化ApplicationContext之后会马上初始化BeanFacory
从类结构里我们能找到这个方法来自它的父类: AbstractApplicationContext 在它的 refresh() 方法内我们可以看到 spring 的复杂逻辑。首先执行了refreshBeanFactory(); (来自 AbstractRefreshableApplicationContext )见 (a),
(a)refreshBeanFactory(); 这个方法由负责维护变量 beanFactory 的子类AbstractRefreshableApplicationContext 实现,默认情况下
这个方法直接实例化一个新的 DefaultListableBeanFactory 类型的 BeanFacorty,
java 代码
protected final void refreshBeanFactory() throws BeansException { DefaultListableBeanFactory beanFactory = createBeanFactory(); customizeBeanFactory(beanFactory); loadBeanDefinitions(beanFactory); } protected DefaultListableBeanFactory createBeanFactory() { return new DefaultListableBeanFactory(getInternalParentBeanFactory()); } AbstractApplicationContext.java protected BeanFactory getInternalParentBeanFactory() {//判断用的是ApplicationContext or BeanFactory
return (getParent() instanceof ConfigurableApplicationContext) ? ((ConfigurableApplicationContext) getParent()).getBeanFactory() : (BeanFactory) getParent(); } public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry {} XmlWebApplicationContext.java--> /** * Loads the bean definitions via an XmlBeanDefinitionReader. * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader * @see #initBeanDefinitionReader * @see #loadBeanDefinitions */ 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); } public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { } XmlBeanDefinitionReader 继承了 AbstractBeanDefinitionReader,AbstractBeanDefinitionReader的构造函数如下: protected AbstractBeanDefinitionReader(BeanDefinitionRegistry beanFactory) {//DefaultListableBeanFactory实现了
//BeanDefinitionRegistry
Assert.notNull(beanFactory, "Bean factory must not be null"); this.beanFactory = beanFactory; // Determine ResourceLoader to use.如果beanFactory不但实现了BeanDefinitionRegistry,而且实现了ResourceLoader
//通常的这样的情况是实现了org.springframework.context.ApplicationContext的BeanFactory,这一点可以查看(c)部分
if (this.beanFactory instanceof ResourceLoader) { this.resourceLoader = (ResourceLoader) this.beanFactory; }else { this.resourceLoader = new PathMatchingResourcePatternResolver(); } }
初始化完了AbstractBeanDefinitionReader之后,继续XmlBeanDefinitionReaderd的初始化:
java 代码
public XmlBeanDefinitionReader(BeanDefinitionRegistry beanFactory) { if (getResourceLoader() != null) {//getResourceLoader已经得到
this.entityResolver = new ResourceEntityResolver(getResourceLoader()); //entityResolver
}else { this.entityResolver = new DelegatingEntityResolver(ClassUtils.getDefaultClassLoader()); } }
上面的初始化相当于初始化了 XmlBeanDefinitionReader的resourceLoader和entityResolver
然后就是对各个配置路径的初始化工作:
java 代码
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { String[] configLocations = getConfigLocations(); if (configLocations != null) { for (int i = 0; i < configLocations.length; i++) { reader.loadBeanDefinitions(configLocations[i]); } } }
XmlBeanDefinitionReader中的初始化工作,因此所有的xml的解析实际上是在这个类文件中完成的
java 代码
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException { InputStream inputStream = encodedResource.getResource().getInputStream(); try { InputSource inputSource = new InputSource(inputStream); if (encodedResource.getEncoding() != null) { inputSource.setEncoding(encodedResource.getEncoding()); } return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); } finally{ inputStream.close(); } }catch (IOException ex) { throw new BeanDefinitionStoreException( "IOException parsing XML document from " + encodedResource.getResource(), ex); } } protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException { int validationMode = getValidationModeForResource(resource); Document doc = this.documentLoader.loadDocument(//获得解析的dom路径
inputSource, this.entityResolver, this.errorHandler, validationMode, this.namespaceAware); return registerBeanDefinitions(doc, resource); } (c) public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext, DisposableBean{};//AbstractApplicationContext继承了DefaultResourceLoader
public class DefaultResourceLoader implements ResourceLoader{}//DefaultResourceLoader实现了ResourceLoader
public DefaultResourceLoader() {//构造函数
this.classLoader = ClassUtils.getDefaultClassLoader(); } public static ClassLoader getDefaultClassLoader() { cl = Thread.currentThread().getContextClassLoader();//取得Application级的ClassLoader
}
然后调用一个起缓冲作用的配置函数生成一个将 beanFacroty 包装起来的对象 beanDefinitionReader ,然后对这个对象进行属性配置,实际上该方法主要负责生成一个临时的操作对象,对应调用的函数为“loadBeanDefinitions(beanFactory);”该方法为初始化期间较为重要的一个。该方法来自其子类:AbstractRefreshableWebApplicationContext
java 代码
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { String[] configLocations = getConfigLocations();// xml文件的配置的路径
if (configLocations != null) { for (int i = 0; i < configLocations.length; i++) { reader.loadBeanDefinitions(configLocations[i]); } } }
对应的函数:
protected void loadBeanDefinitions(DefaultListableBeanFactory) ,然后这里又调用了自己定义的
protected void loadBeanDefinitions(XmlBeanDefinitionReader) 方法。此时,它就使用到了在以前中设置了的( wac.setConfigLocations(……)) 我们开发中密切相关的配置文件。(同时也要记住此时这个函数的参数 beanDefinitionReader ,之前已经设置了”beanDefinitionReader.setResourceLoader(this) “这里的 this 是我们在前面见到的 XmlWebApplicationContext (一个定义好了的上下文))。接着往下:reader.loadBeanDefinitions(configLocations[i]); reader 开始加载我们配置文件内的东西了,不过真正复杂的实现此时才开始,我们继续往下走,在接下来的方法内默认情况下会执行:if (resourceLoader instanceof ResourcePatternResolver)(该判断条件为true ),由于从上面我们知道: beanDefinitionReader.setResourceLoader(this); 而 this 的类型为: XmlWebApplicationContext所以 ((ResourcePatternResolver) resourceLoader).getResources(location); 得到一个 Resource[] 数组,接下来调用:int loadCount = loadBeanDefinitions(resources); 该函数继续调用自己子类定义的一系列临时接口最终执行到 return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); 在这个函数内初始化了处理 xml 文件的一些对象并将用户的配置文件解析为一个 Document 对象。然后又执行了一系列函数直到return parser.registerBeanDefinitions(this, doc, resource); 这个函数来自我们新建的 DefaultXmlBeanDefinitionParser,在这个类里最终执行了对 xml 文件的解析工作和对 beanFacroty 变量执行了设置工作。
(b)终于我们从这些繁杂的逻辑中跳了出来,继续执行 AbstractApplicationContext.refresh() 下面的工作,后续的代码主要仍旧是往一些常量里面设值。
此时 Spring BeanFactory初始化过程就结束了。
|