[源码系列:手写spring] IOC第五节:Bean注入Bean

主要内容

添加BeanReference类,包装一个bean对另一个bean的引用。如beanA引用beanB,那么在实例化beanA时,如果propertyValue.value是BeanReference类型,引用beanB,那么先实例化beanB。在这里为了便于大家理解暂时不引入三级缓存解决循环依赖,三级缓存会在后面高级篇单独讲解。

代码分支

populate-bean-with-bean

核心代码

BeanReference

public class BeanReference {
    private String name;

    public BeanReference(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

AbstractAutowireCapableBeanFactory.applyPropertyValues方法

    private void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        for(PropertyValue propertyValue : beanDefinition.getPropertyValues().getPropertyValues()){
            String name = propertyValue.getName();
            Object value = propertyValue.getValue();
            if(value instanceof BeanReference){
                BeanReference beanReference = (BeanReference)value;
                value = getBean(beanReference.getName());
            }
            BeanUtil.setProperty(bean,name,value);
        }
    }

测试

@Test    
public void testBeanWithBean(){
        PropertyValues propertyValuesForPerson = new PropertyValues();
        propertyValuesForPerson.addPropertyValue(new PropertyValue("name","yiHui"));
        propertyValuesForPerson.addPropertyValue(new PropertyValue("age",20));
        propertyValuesForPerson.addPropertyValue(new PropertyValue("car",new BeanReference("car")));

        PropertyValues propertyValuesForCar = new PropertyValues();
        propertyValuesForCar.addPropertyValue(new PropertyValue("name","Rolls-Royce"));

        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();

        factory.registerBeanDefinition("car",new BeanDefinition(Car.class,propertyValuesForCar));
        factory.registerBeanDefinition("person",new BeanDefinition(Person.class,propertyValuesForPerson));

        Person person = (Person)factory.getBean("person");
        System.out.println(person);
    }

测试结果

Person{name='yiHui', age='20', car=Car{name='Rolls-Royce'}}
posted @ 2023-03-20 22:31  yihuiComeOn  阅读(11)  评论(0)    收藏  举报  来源