Spring核心源码

原创
2017/06/19 10:52
阅读数 274

一、常见的初始化方式

spring常见的初始化方式有如下几种:

1. main函数里使用ClassPathXmlApplicationContext

public static void main(String[] args) {
    ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath*:/spring/test/appcontext-dependencies.xml");
    Thread.currentThread().join();
}

2. web.xml通过ContextLoaderListener

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/test/appcontext-dependencies.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

3. web.xml通过DispatcherServlet

<servlet>
    <servlet-name>springDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath*:config/spring/common/appcontext-*.xml,
            classpath*:config/spring/local/appcontext-*.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springDispatcher</servlet-name>
    <url-pattern>/study/*</url-pattern>
</servlet-mapping>

4. spring-test通过SpringJUnit4ClassRunner

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/spring/test/appcontext-dependencies.xml"})

5. spring4.x通过groovy dsl

import org.hibernate.validator.HibernateValidator
import org.springframework.context.support.ReloadableResourceBundleMessageSource
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean

beans {
    xmlns context: "http://www.springframework.org/schema/context"
    xmlns mvc: "http://www.springframework.org/schema/mvc"

    context.'component-scan'('base-package': "com.chenxiaojie.spring4")
    mvc.'annotation-driven'('validator': "validator")

    validator(LocalValidatorFactoryBean) {
        providerClass = HibernateValidator.class
        validationMessageSource = ref("messageSource")
    }
}

6. spring4.x通过全注解(http://jinnianshilongnian.iteye.com/blog/1991830)

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.chenxiaojie.spring4")
public class MvcConfiguration extends WebMvcConfigurationSupport {
    @Override
    protected Validator getValidator() {
        LocalValidatorFactoryBean localValidatorFactoryBean =
                new LocalValidatorFactoryBean();
        localValidatorFactoryBean.setProviderClass(HibernateValidator.class);
        localValidatorFactoryBean.setValidationMessageSource(messageSource());
        return localValidatorFactoryBean;
    }
}

 

二、初始化流程

无论是上方的哪一种初始化方式最后context初始化代码都是下方的refresh方法,这是典型的模板方法设计模式。

AbstractApplicationContext:

public void refresh() throws BeansException, IllegalStateException {

   // 同步块决定了spring的初始化一定是单线程的(spring作为bean容器默认只初始化一次, 多线程提高初始化速度并没有什么意义)
   synchronized (this.startupShutdownMonitor) {

      // 预准备refresh, 检查environment参数是否合理
      prepareRefresh();

      // 构造beanFactory, 里面包含所有beanDefinition加载, 主要是解析xml和注解
      // 参考AbstractRefreshableApplicationContext->refreshBeanFactory->loadBeanDefinitions方法
      // 参考AbstractBeanDefinitionReader->loadBeanDefinitions(String location, Set<Resource> actualResources)
      // 参考XmlBeanDefinitionReader->loadBeanDefinitions(EncodedResource encodedResource)
      // 参考DefaultBeanDefinitionDocumentReader->doRegisterBeanDefinitions(Element root)
      // 参考ContextNamespaceHandler->ComponentScanBeanDefinitionParser->parse->ClassPathBeanDefinitionScanner->doScan
      // 参考ClassPathScanningCandidateComponentProvider->findCandidateComponents(String basePackage)
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // 预准备beanFactory, 设置基本环境变量
      prepareBeanFactory(beanFactory);

      try {
         // 默认为空实现
         postProcessBeanFactory(beanFactory);

         // 添加实现了PriorityOrdered优先级极高的处理器, 这个环节只走半生命周期, 因为在new的时候postProcessors还未初始化完毕
         // org.springframework.context.annotation.internalConfigurationAnnotationProcessor
         invokeBeanFactoryPostProcessors(beanFactory);

         // 添加实现了Ordered的处理器,
         // org.springframework.context.annotation.internalAutowiredAnnotationProcessor
         // org.springframework.context.annotation.internalRequiredAnnotationProcessor
         // org.springframework.context.annotation.internalCommonAnnotationProcessor
         // org.springframework.aop.config.internalAutoProxyCreator
         // org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
         registerBeanPostProcessors(beanFactory);

         // 初始化消息
         initMessageSource();

         // 初始化事件处理器
         initApplicationEventMulticaster();

         // 默认空实现
         onRefresh();

         // 注册所有的spring监听器
         registerListeners();

         // 实现化所有业务相关的单例bean
         finishBeanFactoryInitialization(beanFactory);

         // 执行Lifecycle/事件通知等事务
         finishRefresh();
      }

      catch (BeansException ex) {
         // 销毁所有bean
         destroyBeans();

         cancelRefresh(ex);

         throw ex;
      }
   }
}

 

结构图

xml解析处理器

prepareBeanFactory给beanFactory实例化了三个bean

invokeBeanFactoryPostProcessors初始化实现了PriorityOrdered的处理器

registerBeanPostProcessors初始化实现了Ordered的处理器

 

展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部