Spring DispatcherServlet MVC 源码分析(BeanFactory的初始化)

本文详细解析了Spring MVC的初始化过程,重点关注了BeanFactory的初始化触发机制。从FrameworkServlet中的wac.refresh()方法出发,深入探讨了XmlWebApplicationContext的实例化过程及BeanFactory的创建与配置。

BeanFactory的初始化的触发——><o:p></o:p>

FrameworkServlet中的wac.refresh()<o:p></o:p>

<o:p> </o:p>
如下为初始化
MVC部分的操作:<o:p></o:p>

java 代码
  1. initmultipartresolver();  
  2. initlocaleresolver();  
  3. initthemeresolver();  
  4. inithandlermappings();  
  5. inithandleradapters();  
  6. inithandlerexceptionresolvers();  
  7. initviewresolver();  

<o:p></o:p>

<o:p> </o:p>

现在有一个疑问 initHandlerMappings(ApplicationContext context)中的ApplicationContext的实现在web中是哪一个,可以从下面得到结论<o:p></o:p>

<o:p> </o:p>

java 代码
 
  1. public static final Class DEFAULT_CONTEXT_CLASS = XmlWebApplicationContext.class;  
  2. private Class contextClass = DEFAULT_CONTEXT_CLASS;  

<o:p></o:p>

<o:p> </o:p>

可以看出这个地方是实例化的是XmlWebApplicationContext的一个实例,那么这个实例是在哪个地方被实例化的呢?在DispatchServelet的父类FrameworkServlet中可以找到如下的代码,<o:p></o:p>

<o:p> </o:p>

java 代码
  1. WebApplicationContext parent = WebApplicationContextUtils.getWebApplicationContext(getServletContext());  
  2. WebApplicationContext wac = createWebApplicationContext(parent);  

<o:p></o:p>

<o:p> </o:p>

ok,我们现在就可以用这个wac了,顺便看看这个实例里边都有什么东西:<o:p></o:p>

<o:p> </o:p>

java 代码
 
  1. wac.setParent(parent);//web.xml中加载的context  
  2. wac.setServletContext(getServletContext());  
  3. wac.setServletConfig(getServletConfig());  
  4. wac.setNamespace(getNamespace());  
  5. if (getContextConfigLocation() != null) {  
  6.     wac.setConfigLocations(  
  7.     StringUtils.tokenizeToStringArray(  
  8.     getContextConfigLocation(), ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));  
  9. }//比较有用  
  10. wac.addApplicationListener(this);  

<o:p></o:p>

<o:p> </o:p>

继续我们的MVC探索--><o:p></o:p>

下面是MVC的部分,提前分析一下<o:p></o:p>

java 代码
 
  1. protected List getDefaultStrategies(ApplicationContext context, Class strategyInterface) throws BeansException {  
  2.     String key = strategyInterface.getName();//equals org.springframework.web.servlet.HandlerMapping  
  3.     List strategies = null;  
  4.     String value = defaultStrategies.getProperty(key);  
  5.     //org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping.class  
  6.     if (value != null) {  
  7.         String[] classNames = StringUtils.commaDelimitedListToStringArray(value);//等效于split  
  8.         strategies = new ArrayList(classNames.length);  
  9.         for (int i = 0; i < classNames.length; i++) {  
  10.             String className = classNames[i];  
  11.             try {  
  12.                 Class clazz = ClassUtils.forName(className, getClass().getClassLoader());  
  13.                 Object strategy = createDefaultStrategy(context, clazz);  
  14.                 strategies.add(strategy);  
  15.             }  
  16.             catch (ClassNotFoundException ex) {  
  17.                 throw new BeanInitializationException(  
  18.                     "Could not find DispatcherServlet's default strategy class [" + className +  
  19.                     "] for interface [" + key + "]", ex);  
  20.             }  
  21.             catch (LinkageError err) {  
  22.                 throw new BeanInitializationException(  
  23.                     "Error loading DispatcherServlet's default strategy class [" + className +  
  24.                     "] for interface [" + key + "]: problem with class file or dependent class", err);  
  25.             }  
  26.         }  
  27.     }else {  
  28.         strategies = Collections.EMPTY_LIST;  
  29.     }  
  30.     return strategies;  
  31. }  
  32.   
  33. protected Object createDefaultStrategy(ApplicationContext context, Class clazz) throws BeansException {  
  34.     return context.getAutowireCapableBeanFactory().createBean(  
  35.         clazz, AutowireCapableBeanFactory.AUTOWIRE_NO, false);  
  36.         //org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping.class  
  37. }  

<o:p></o:p>

context XmlWebApplicationContext的一个实例,而<o:p></o:p>

<o:p> </o:p>

java 代码
 
  1. public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext  
  2.   
  3. public abstract class AbstractRefreshableWebApplicationContext extends AbstractRefreshableApplicationContext  
  4. implements ConfigurableWebApplicationContext, ThemeSource  
  5.   
  6. public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext   
  7.   
  8. public abstract class AbstractApplicationContext extends DefaultResourceLoader  
  9. implements ConfigurableApplicationContext, DisposableBean {  
  10.     public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException {  
  11.         return getBeanFactory();  
  12.     }  
  13. }  
  14.   
  15. 在AbstractRefreshableApplicationContext中  
  16. public final ConfigurableListableBeanFactory getBeanFactory() {  
  17.     synchronized (this.beanFactoryMonitor) {  
  18.         if (this.beanFactory == null) {  
  19.             throw new IllegalStateException("BeanFactory not initialized or already closed - " +  
  20.             "call 'refresh' before accessing beans via the ApplicationContext");  
  21.         }  
  22.         return this.beanFactory;  
  23.     }  
  24. }  

<o:p>

说明这个时候BeanFactory已经初始化好了,那么在哪个地方初始化好的呢?可以想象到的地方就是XmlWebApplicationContextnew的时候会初始化这个BeanFactory?在WebApplicationContext createWebApplicationContext(WebApplicationContext parent)时候,也就是在初始化ApplicationContext的时候有如下操作<o:p></o:p>

<o:p> </o:p>

wac.refresh();<o:p></o:p>

<o:p> </o:p>

也就是初始化ApplicationContext之后会马上初始化BeanFacory<o:p></o:p>

从类结构里我们能找到这个方法来自它的父类: AbstractApplicationContext 在它的 refresh() 方法内我们可以看到 spring 的复杂逻辑。首先执行了refreshBeanFactory(); (来自 AbstractRefreshableApplicationContext )见 (a),<o:p></o:p>

<o:p> </o:p>

(a)refreshBeanFactory(); 这个方法由负责维护变量 beanFactory 的子类AbstractRefreshableApplicationContext 实现,默认情况下<o:p></o:p>

这个方法直接实例化一个新的 DefaultListableBeanFactory 类型的 BeanFacorty, <o:p></o:p>

java 代码
 
  1. protected final void refreshBeanFactory() throws BeansException {  
  2.     DefaultListableBeanFactory beanFactory = createBeanFactory();  
  3.     customizeBeanFactory(beanFactory);  
  4.     loadBeanDefinitions(beanFactory);  
  5. }  
  6. protected DefaultListableBeanFactory createBeanFactory() {  
  7.     return new DefaultListableBeanFactory(getInternalParentBeanFactory());  
  8. }  
  9.   
  10. AbstractApplicationContext.java  
  11. protected BeanFactory getInternalParentBeanFactory() {//判断用的是ApplicationContext or BeanFactory   
  12.     return (getParent() instanceof ConfigurableApplicationContext) ?  
  13.         ((ConfigurableApplicationContext) getParent()).getBeanFactory() : (BeanFactory) getParent();  
  14. }  
  15. public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory  
  16. implements ConfigurableListableBeanFactory, BeanDefinitionRegistry {}  
  17.   
  18. XmlWebApplicationContext.java-->  
  19. /** 
  20. * Loads the bean definitions via an XmlBeanDefinitionReader. 
  21. * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader 
  22. * @see #initBeanDefinitionReader 
  23. * @see #loadBeanDefinitions 
  24. */  
  25. protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {  
  26.     // Create a new XmlBeanDefinitionReader for the given BeanFactory.  
  27.     XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);  
  28.   
  29.     // Configure the bean definition reader with this context's  
  30.     // resource loading environment.  
  31.     beanDefinitionReader.setResourceLoader(this);  
  32.     beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));  
  33.   
  34.     // Allow a subclass to provide custom initialization of the reader,  
  35.     // then proceed with actually loading the bean definitions.  
  36.     initBeanDefinitionReader(beanDefinitionReader);  
  37.     loadBeanDefinitions(beanDefinitionReader);  
  38. }  
  39. public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {  
  40. }  
  41. XmlBeanDefinitionReader 继承了 AbstractBeanDefinitionReader,AbstractBeanDefinitionReader的构造函数如下:  
  42. protected AbstractBeanDefinitionReader(BeanDefinitionRegistry beanFactory) {//DefaultListableBeanFactory实现了  
  43.                                         //BeanDefinitionRegistry   
  44.     Assert.notNull(beanFactory, "Bean factory must not be null");  
  45.     this.beanFactory = beanFactory;  
  46.     // Determine ResourceLoader to use.如果beanFactory不但实现了BeanDefinitionRegistry,而且实现了ResourceLoader   
  47.     //通常的这样的情况是实现了org.springframework.context.ApplicationContext的BeanFactory,这一点可以查看(c)部分  
  48.     if (this.beanFactory instanceof ResourceLoader) {  
  49.         this.resourceLoader = (ResourceLoader) this.beanFactory;  
  50.     }else {  
  51.         this.resourceLoader = new PathMatchingResourcePatternResolver();  
  52.     }  
  53. }  

<o:p></o:p>

初始化完了AbstractBeanDefinitionReader之后,继续XmlBeanDefinitionReaderd的初始化:<o:p></o:p>

java 代码
 
  1. public XmlBeanDefinitionReader(BeanDefinitionRegistry beanFactory) {  
  2.     if (getResourceLoader() != null) {//getResourceLoader已经得到  
  3.         this.entityResolver = new ResourceEntityResolver(getResourceLoader());  
  4.         //entityResolver  
  5.     }else {  
  6.         this.entityResolver = new DelegatingEntityResolver(ClassUtils.getDefaultClassLoader());  
  7.     }  
  8. }  

<o:p></o:p>

上面的初始化相当于初始化了 XmlBeanDefinitionReaderresourceLoaderentityResolver<o:p></o:p>

然后就是对各个配置路径的初始化工作:<o:p></o:p>

java 代码
 
  1. protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {  
  2.     String[] configLocations = getConfigLocations();  
  3.     if (configLocations != null) {  
  4.         for (int i = 0; i < configLocations.length; i++) {  
  5.             reader.loadBeanDefinitions(configLocations[i]);  
  6.         }  
  7.     }  
  8. }  

<o:p></o:p>

XmlBeanDefinitionReader中的初始化工作,因此所有的xml的解析实际上是在这个类文件中完成的 <o:p></o:p>

java 代码
 
  1. public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {  
  2.     InputStream inputStream = encodedResource.getResource().getInputStream();  
  3.     try {  
  4.         InputSource inputSource = new InputSource(inputStream);  
  5.         if (encodedResource.getEncoding() != null) {  
  6.             inputSource.setEncoding(encodedResource.getEncoding());  
  7.         }  
  8.         return doLoadBeanDefinitions(inputSource, encodedResource.getResource());  
  9.         }  
  10.         finally{  
  11.             inputStream.close();  
  12.         }  
  13.     }catch (IOException ex) {  
  14.         throw new BeanDefinitionStoreException(  
  15.         "IOException parsing XML document from " + encodedResource.getResource(), ex);  
  16.     }  
  17. }  
  18. protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)  
  19.     throws BeanDefinitionStoreException {  
  20.     int validationMode = getValidationModeForResource(resource);  
  21.     Document doc = this.documentLoader.loadDocument(//获得解析的dom路径  
  22.         inputSource, this.entityResolver, this.errorHandler, validationMode, this.namespaceAware);  
  23.     return registerBeanDefinitions(doc, resource);  
  24. }  
  25.   
  26. (c)  
  27. public abstract class AbstractApplicationContext extends DefaultResourceLoader  
  28. implements ConfigurableApplicationContext, DisposableBean{};//AbstractApplicationContext继承了DefaultResourceLoader  
  29. public class DefaultResourceLoader implements ResourceLoader{}//DefaultResourceLoader实现了ResourceLoader  
  30. public DefaultResourceLoader() {//构造函数  
  31.         this.classLoader = ClassUtils.getDefaultClassLoader();  
  32. }  
  33. public static ClassLoader getDefaultClassLoader() {   
  34.     cl = Thread.currentThread().getContextClassLoader();//取得Application级的ClassLoader      
  35. }  

<o:p></o:p>

<o:p> </o:p>

<o:p> </o:p>

然后调用一个起缓冲作用的配置函数生成一个将 beanFacroty 包装起来的对象 beanDefinitionReader ,然后对这个对象进行属性配置,实际上该方法主要负责生成一个临时的操作对象,对应调用的函数为“loadBeanDefinitions(beanFactory);”该方法为初始化期间较为重要的一个。该方法来自其子类:AbstractRefreshableWebApplicationContext <o:p></o:p>

<o:p>

java 代码
 
  1. protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {  
  2.     String[] configLocations = getConfigLocations();// xml文件的配置的路径  
  3.     if (configLocations != null) {  
  4.         for (int i = 0; i < configLocations.length; i++) {  
  5.             reader.loadBeanDefinitions(configLocations[i]);  
  6.         }  
  7.     }  
  8. }  

<o:p>

对应的函数:<o:p></o:p>

protected void loadBeanDefinitions(DefaultListableBeanFactory) ,然后这里又调用了自己定义的 <o:p></o:p>

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 变量执行了设置工作。<o:p></o:p>

<o:p> </o:p>

(b)终于我们从这些繁杂的逻辑中跳了出来,继续执行 AbstractApplicationContext.refresh() 下面的工作,后续的代码主要仍旧是往一些常量里面设值。<o:p></o:p>

<o:p> </o:p>

此时 Spring BeanFactory初始化过程就结束了。
内容概要:本文研究了一种基于遗传算法(GA)与粒子群优化算法(PSO)融合的无人机三维路径规划方法,旨在解决复杂环境中无人机避障与路径优化的问题。通过构建三维空间环境模型,提出一种结合GA全局搜索能力强与PSO收敛速度快优势的混合优化策略,并利用Matlab平台完成算法仿真与路径可视化。研究不仅实现了无人机在存在多个障碍物场景下的安全、高效飞行路径规划,还对GA与PSO两种算法在路径长度、计算耗时、收敛稳定性等方面进行了对比分析,评估其性能差异,为实际应用中算法选型提供依据。; 适合人群:具备一定算法设计基础和Matlab编程能力的科研人员、自动化与人工智能方向的研究生,以及从事无人机导航、智能控制等相关领域的工程技术人员。; 使用场景及目标:①应用于城市密集建筑区、山地森林等复杂地形中的无人机自主巡检与应急救援任务;②为智能交通、地理测绘、灾害监测等需要自主路径决策的无人系统提供算法支持与仿真验证;③通过对比不同智能优化算法的表现,辅助研究人员在特定应用场景下选择最优路径规划方案。; 阅读建议:建议读者结合提供的Matlab代码进行仿真实验,调整种群规模、迭代次数、障碍物分布等参数,深入理解算法运行机制与性能表现,并可进一步拓展至动态环境更新、多无人机协同避障等更复杂的研究方向。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值