Spring源码学习笔记之一:从BeanPostProcesser开始

来源:互联网 发布:扬州网络电视台回看 编辑:程序博客网 时间:2024/06/15 22:08

对Spring的源码之前没有系统的阅读过,现在有点时间正好仔细的学习一下。
我觉得带着问题去学习源码是速度比较快的一种方式,好过漫无目的的浏览,那样看起来也比较吃力。
第一部分就从BeanPostProcesser(不了解的参照:http://blog.csdn.net/xuechongyang/article/details/17683225)这个东西入手,
因为刚发现这个东西的时候解决了一个困扰了我几天的问题,于是就顺藤摸瓜想了解一下再Spring中是怎么实现它的。这就需要从Spring
是怎么从监听器ContextLoaderListener启动来看了。
首先来看Spring从监听器ContextLoaderListener的启动过程,看了一篇文章(http://hi.baidu.com/32647908/item/b6306c4132f5dcf4dc0f6c41)
发现和Spring的源码有点对不上,我们这里用的Spring3.1.1,于是自己重新总结了一下:
1. ContextLoaderListener实现了ServletContextListener接口,所以有contextInitialized方法:
public void contextInitialized(ServletContextEvent event) {       this.contextLoader = createContextLoader();       if (this.contextLoader == null) {            this.contextLoader = this;       }       this.contextLoader.initWebApplicationContext(event.getServletContext());}

2. 进入 initWebApplicationContext()方法,有这么一段代码:
if (this.context == null) {    this.context = createWebApplicationContext(servletContext);}if (this.context instanceof ConfigurableWebApplicationContext) {    configureAndRefreshWebApplicationContext((ConfigurableWebApplicationContext)this.context, servletContext);}

3. configureAndRefreshWebApplicationContext()这个方法比较重要,方法前面部分似乎生成ID,不去管它,看后面的部分:
// Determine parent for root web application context, if any.ApplicationContext parent = loadParentContext(sc);wac.setParent(parent);wac.setServletContext(sc);String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM);if (initParameter != null) {    wac.setConfigLocation(initParameter);}customizeContext(sc, wac);wac.refresh();

4. was.refresh()是下一步的重点,进入AbstractApplicationContext类的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);// 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;}}}

5. 从注释就能知道registerBeanPostProcessors()方法是我们要找的东西,第一句就是
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
我们知道自己定义的SpringDataSourceBeanPostProcessor实现了BeanPostProcessor,经过调试,发现在Spring启动的时候确实在这里被加载了。

下面就是通过名字将我们定义的SpringDataSourceBeanPostProcessor加载到内存的过程:

for (String ppName : postProcessorNames) {if (isTypeMatch(ppName, PriorityOrdered.class)) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);priorityOrderedPostProcessors.add(pp);if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);}}else if (isTypeMatch(ppName, Ordered.class)) {orderedPostProcessorNames.add(ppName);}else {nonOrderedPostProcessorNames.add(ppName);}}


6. 发现什么了?我们发现了beanFactory.getBean()方法,这似乎就是Spring IOC的实现关键,顺藤摸瓜去看看:
  费了半天劲,发现这个getBean()方法的实现在AbstractBeanFactory类中:
  public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return doGetBean(name, requiredType, null, false);
}
  然后就找到了非常非常关键的doGetBean()方法。

7. 这里留在以后研究加载bean的过程的时候再看,差点跑题了,继续我们的问题:BeanPostProcessor是怎么在受管bean创建时被回调的?
继续阅读AbstractApplicationContext类的registerBeanPostProcessors()方法,发现最后都调用了AbstractBeanFactory类的addBeanPostProcessor()方法。
这样就又回到了AbstractBeanFactory,发现有一个getBeanPostProcessors()是返回beanPostProcessors列表的,我们用eclipse的open call Hierarchy功能
查看哪些类的哪些方法调用了此方法:发现了AbstractAutowireCapableBeanFactory这个类用到了,然后跟着它的applyBeanPostProcessorsAfterInitialization()
方法,再找applyBeanPostProcessorsAfterInitialization()方法的调用类,又找到了SpringObjectFactory的buildBean()方法,这应该就是使用AutoWire注解
的bean的构建方法。在buildBean()方法中就用到了我们自定义的BeanPostProcessor。

8.这里我们大概了解了Spring的自定义BeanPostProcessor从加载到被调用的过程,但是肯定不全面,这里只是一个带着问题去研究Spring源码的例子,希望有错误之处能帮我指正。

0 0
原创粉丝点击