上一篇 IOC容器从BeanFactory获取Bean源码浅析中,实例化bean到IOC容器中,是通过默认无参构造器来实例化的,没有涉及到Bean的依赖注入问题。现补上。
bean依赖注入过程,首先实例化,可以通过构造器实例化,也可以通过cblib代理实例化。然后解析属性值,如果是基本类型,则不需要解析,如果是对象的引用类型,则要实例化该属性的引用对象。最后通过反射机制对对象属性赋值,完成bean的依赖注入。
Demo:
public class BeanExample {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
StudentService studentService = (StudentService) applicationContext.getBean("studentService");
studentService.hello();
}
}
<bean id="userService" class="com.hand.user.dal.UserServiceImpl" scope="prototype"/> <!--指定实例化类型为原型-->
<bean id="