[源码系列:手写spring] IOC第三节:Bean实例化策略InstantiationStrategy

主要内容

在第二节中AbstractAutowireCapableBeanFactory类中使用class.newInstance()的方式创建实例,仅适用于无参构造器。  大家可以测试一下,将第二节的测试类UserService添加有参构造,运行测试就会报错。

org.springframework.beans.BeansException: Instantiation of bean failed

	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean
    ...

针对bean的实例化,本节将抽象出一个实例化策略的接口InstantiationStrategy,有两个实现类:

  • SimpleInstantiationStrategy,使用bean的构造函数来实例化
  • CglibSubclassingInstantiationStrategy,使用CGLIB动态生成子类

 

代码分支

代码分支:instantiation_strategy

 

类图

 

策略相关类图

策略模式介绍

拿做年夜饭举例,你现在原材料里有排骨肉等,在纠结如何做排骨肉,所以你打开了做排骨策略宝盒 (策略接口,里面放排骨肉具体做法的排骨宝典),当里面是清蒸宝典时(多态,策略接口变量可以接受不同实现类实例),那么你就用清蒸的策略去做。

测试

添加有参构造的参数

    @Test
    public void test() {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        BeanDefinition beanDefinition = new BeanDefinition();
        beanDefinition.setClazz(UserService.class);
        beanFactory.registerBeanDefinition("userService", beanDefinition);
        UserService userService = (UserService)beanFactory.getBean("userService","YiHui") ;
        userService.save();
    }

测试结果

save_success

Process finished with exit code 0

 

posted @ 2023-02-21 17:05  yihuiComeOn  阅读(14)  评论(0)    收藏  举报  来源