[源码系列:手写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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值