Spring 框架源码解读6


title: Spring 框架源码解读6
date: 2020/04/17 14:54


本节内容 & 思考题

Spring 给了我们 3 个接口让我们在它初始化的时候,分别对 BeanFactory、BeanDefinitionRegistry 还有 Bean 进行干预,今天就让我们来实现这个吧。

还记得处理 @PostConstruct 注解那个地方吧,为什么在 Spring 中是采用后置处理器实现的?


开闭原则:后置处理器

BeanDefinitionRegistryPostProcessor

1、新增 BeanDefinitionRegistry 接口,ListableBeanFactory 接口继承它, ListableBeanFactoryImpl 实现它

public interface BeanDefinitionRegistry {

    /**
     * 注册 bd 到 bf
     */
    void registerBeanDefinition(String name, BeanDefinition beanDefinition);
}

ListableBeanFactoryImpl 中本身就有这个方法,我们只需要加上 @Overwirte 就好了。

2、新增 BeanDefinitionRegistryPostProcessor 接口

/**
 * 使我们可以在 BeanFactory 初始化好了之后,向其中注册 BD
 * <p>
 * 在 Spring 5.0 中它继承了 BeanFactoryPostProcessor 但是我觉得没必要
 */
public interface BeanDefinitionRegistryPostProcessor {
    
    void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry);

}

3、修改 AbstractApplicationContext#refresh()

所以要使用 BeanDefinitionRegistryPostProcessor 就必须要使用 ApplicationContext。

@Override
public void refresh() {

    // 初始化 BF,生成 BF,好在调用 getBeanFactory() 时返回
    this.refreshBeanFactory();

    // 执行 BeanDefinitionRegistryPostProcessor
    this.invokeBeanDefinitionRegistryPostProcessors();

    ...
}

private void invokeBeanFactoryPostProcessors() {
    ListableBeanFactory beanFactory = this.getBeanFactory();

    for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanFactory.getBeansOfType(BeanFactoryPostProcessor.class).values()) {
        // beanFactory 就是那个 registry
        beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
    }
}

4、这个我没测试

集成 BeanFactoryPostProcessor

1、新增 BeanFactoryPostProcessor 接口

public interface BeanFactoryPostProcessor {

    /**
     * 在工厂实例化后做些什么
     */
    void postProcessBeanFactory(ListableBeanFactory beanFactory);

}

2、修改 AbstractApplicationContext#refresh()

所以要使用 BeanFactoryPostProcessor 也必须要使用 ApplicationContext。

@Override
public void refresh() {

    // 初始化 BF,生成 BF,好在调用 getBeanFactory() 时返回
    this.refreshBeanFactory();

    // 执行 BeanDefinitionRegistryPostProcessor
    this.invokeBeanDefinitionRegistryPostProcessors();

    // 执行 BeanFactoryPostProcessor
    this.invokeBeanFactoryPostProcessors();

    ...
}

private void invokeBeanFactoryPostProcessors() {
    ListableBeanFactory beanFactory = this.getBeanFactory();

    for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanFactory.getBeansOfType(BeanFactoryPostProcessor.class).values()) {
        beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
    }
}

3、我也没测试

重头戏 BeanPostProcessor

1、新增接口 BeanPostProcessor

public interface BeanPostProcessor {

    /**
     * 在bean的初始化之前执行
     */
    default Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    /**
     * 在bean的初始化后执行
     */
    default Object postProcessAfterInitialization(Object bean, String beanName) {
        return bean;
    }

}

2、修改 AbstractBeanFactory#createBean 方法

所以, BeanPostProcessor 不依赖 ApplicationContext

// BeanFactory 新增方法

default void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
}

public abstract class AbstractBeanFactory implements BeanFactory {

    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    /**
    * 根据 bd 创建对象
    * <p>
    * 1)创建bean 日后需要对有参构造进行扩展
    * 2)注入属性(Spring 源码中 2 是在 3456 的后面)
    * 3)调用部分 Aware 的方法
    * 4)后置处理器的前置方法
    * 5)执行初始化操作
    * 6)后置处理器的后置方法
    * 7)注册销毁的处理
    */
    private Object createBean(BeanDefinition beanDefinition) {
        // 1、创建 bean
        BeanWrapper beanWrapper = this.createBeanInstance(beanDefinition);

        // 2、注入属性 DI (Spring 0.9 中当属性改变时会触发事件,但是默认是关闭的,暂时不知道它为了干啥)
        List<PropertyArgDefinition> properties = beanDefinition.getProperties();
        List<PropertyValue> propertyValueList = this.parseProperties(properties);
        beanWrapper.setPropertyValues(propertyValueList);
        Object bean = beanWrapper.getWrappedInstance();

        // 3、调用部分 Aware 的方法
        
        // 4、后置处理器的前置方法
        this.applyBeanPostProcessorsBeforeInitialization(bean, beanDefinition.getName());

        // 5、执行初始化操作(在 Spring 中是直接调用的该类中的 initializeBean 方法,为了让他面向对象一点,我给他抽出一个类)
        InitializeBeanAdapter initializeBeanAdapter = new InitializeBeanAdapter(bean, beanDefinition);
        initializeBeanAdapter.afterPropertiesSet();

        // 6、后置处理器的后置方法
        this.applyBeanPostProcessorsAfterInitialization(bean, beanDefinition.getName());

        // 7、注册销毁的处理
        if (this.check(beanDefinition, bean)) {
            registry.registerDisposableBean(beanDefinition.getName(), new DisposableBeanAdapter(bean, beanDefinition));
        }
        return bean;
    }

    // 后置方法
    private void applyBeanPostProcessorsAfterInitialization(Object bean, String name) {
        for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
            beanPostProcessor.postProcessAfterInitialization(bean, name);
        }
    }

    // 前置方法
    private void applyBeanPostProcessorsBeforeInitialization(Object bean, String name) {
        for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
            beanPostProcessor.postProcessBeforeInitialization(bean, name);
        }
    }

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        beanPostProcessors.add(beanPostProcessor);
    }

// 修改 JsonBeanFactoryImpl#loadBeanDefinitions 方法,在加载 BD 的时候,把后置处理器加到集合中。

public class JsonBeanFactoryImpl extends ListableBeanFactoryImpl {

    ...

    private void loadBeanDefinitions(JSONArray jsonArray) {
        List<DefaultBeanDefinition> beanDefinitionList = jsonArray.toList(DefaultBeanDefinition.class);
        for (DefaultBeanDefinition bd : beanDefinitionList) {
            super.registerBeanDefinition(bd.getName(), bd);
        }

        // 向 beanPostProcessors 中添加后置处理器
        for (BeanPostProcessor beanPostProcessor : super.getBeansOfType(BeanPostProcessor.class).values()) {
            super.addBeanPostProcessor(beanPostProcessor);
        }
    }

测试1:将 @PostConstruct 注解改为使用后置处理器

原来的地方记得删掉

1、新增 InitAnnotationBeanPostProcessor

/**
 * 此处只实现对 @PostConstruct 注解的处理,@PreDestroy 不实现(Spring 中通过 DestructionAwareBeanPostProcessor 实现)
 *
 * @author yujx
 * @date 2020/04/17 13:26
 */
public class InitAnnotationBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        for (Method method : ReflectUtils.getMethodsByAnnotation(bean.getClass(), PostConstruct.class)) {
            ReflectUtil.invoke(bean, method);
        }
        return bean;
    }
}

2、测试

public class AppleFactory {

    public Apple createApple() {
        Apple apple = new Apple();
        apple.setName("黄元帅");
        return apple;
    }

    @PostConstruct
    public void init() {
        System.out.println("AppleFactory...");
    }
}

apple.json

[
  {
    "name": "appleFactory",
    "className": "cn.x5456.summer.AppleFactory"
  },
  {
    "name": "initAnnotationBeanPostProcessor",
    "className": "cn.x5456.summer.InitAnnotationBeanPostProcessor"
  }
]

TestJsonAP 和 TestJsonBF 都行

完善 AbstractBeanFactory#createBean() 增加 Aware

/**
 * 根据 bd 创建对象
 * <p>
 * 1)创建bean 日后需要对有参构造进行扩展
 * 2)注入属性(Spring 源码中 2 是在 3456 的后面)
 * 3)调用部分 Aware 的方法
 * 4)后置处理器的前置方法
 * 5)执行初始化操作
 * 6)后置处理器的后置方法
 * 7)注册销毁的处理
 */
private Object createBean(BeanDefinition beanDefinition) {

    // 1、创建 bean
    BeanWrapper beanWrapper = this.createBeanInstance(beanDefinition);

    // 2、注入属性 DI (Spring 0.9 中当属性改变时会触发事件,但是默认是关闭的,暂时不知道它为了干啥)
    List<PropertyArgDefinition> properties = beanDefinition.getProperties();
    List<PropertyValue> propertyValueList = this.parseProperties(properties);
    beanWrapper.setPropertyValues(propertyValueList);
    Object bean = beanWrapper.getWrappedInstance();

    // 3、调用部分 Aware 的方法
    this.invokeAwareMethod(bean, beanDefinition.getName());

    ...
}

private void invokeAwareMethod(Object bean, String beanName) {
    if (bean instanceof Aware) {
        if (bean instanceof BeanNameAware) {
            ((BeanNameAware) bean).setBeanName(beanName);
        }
        // else if () ...
    }
}

因为在 BeanFactory 中没有 ApplicationContext 相关的东西,那么怎么注入呢,有一种方式就是在 ApplicationContext#getBean() 方法中对 BF 进行代理,在获取到 bean 之后注入,我们之前也是这样实现的,但是 Spring 逼格很高,它采用了 BeanPostProcessor 实现。

测试2:使用 ApplicationContextAwareProcessor 注入

也记得把之前注入 ApplicationContext 部分代码注释掉 AbstractApplicationContext#configureManagedObject

1、ApplicationContextAwareProcessor

/**
 * 与 ApplicationContext 中相关数据注入的后置处理器
 * <p>
 * 在 bean 初始化完成后注入相关实例
 *
 * @author yujx
 * @date 2020/04/17 14:34
 */
public class ApplicationContextAwareProcessor implements BeanPostProcessor {

    private ApplicationContext applicationContext;

    public ApplicationContextAwareProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 在bean的初始化之前执行
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if (bean instanceof Aware) {
            if (bean instanceof ApplicationContextAware) {
                ((ApplicationContextAware) bean).setApplicationContext(applicationContext);
            }
            // else if () ...
        }
        return bean;
    }
}

2、将新写好的处理器注入 BF 中

public class FileSystemJsonApplicationContext extends AbstractApplicationContext {


    // 与当前 ApplicationContext 相关联的 BF
    private ListableBeanFactory beanFactory;
    
    /**
     * 初始化当前 ApplicationContext 的 BF
     */
    @Override
    protected void refreshBeanFactory() {
        beanFactory = new JsonBeanFactoryImpl(configLocation, super.getParent());

        // beanFactory 初始化完成后,向其中添加一个后置处理器
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    }

3、测试

public class TestJsonAP {

    public static void main(String[] args) {
        FileSystemJsonApplicationContext fileSystemJsonApplicationContext = new FileSystemJsonApplicationContext(new String[]{
                "/Users/x5456/IdeaProjects/Summer/src/test/resources/apple.json"
        });
    }
}

public class AppleFactory implements BeanNameAware, ApplicationContextAware {

    public Apple createApple() {
        Apple apple = new Apple();
        apple.setName("黄元帅");
        return apple;
    }

    @PostConstruct
    public void init() {
        System.out.println("AppleFactory...");
    }

    /**
     * 注入 ApplicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext ctx) {
        System.out.println("ctx = " + ctx);
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("name = " + name);
    }
}

Spring 5.0

BeanFactoryPostProcessor & BeanDefinitionRegistryPostProcessor

image

Spring 考虑了各种注入方式(ap.add、注解、配置文件)和执行顺序问题(Order),导致代码过于复杂,不建议看。

BeanPostProcessor

AbstractAutowireCapableBeanFactory#doCreateBean
image

ApplicationContextAwareProcessor 实现注入功能

BPP 实现 Aware 的注入

思考题答案

因为一开始的时候 Spring 并没有考虑 @PostConsturce 注解,为了符合“开闭原则”,不修改原有代码,所以 Spring 采用了后置处理器完成。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354

推荐阅读更多精彩内容