实现步骤:
bean标签
无参构造方法加载:
1.通过id加载
第一步:加载 spring.xml 配置文件,生成 ApplicationContext 对象。
第二步:调用 ApplicationContext 的 getBean 方法获取对象,参数为配置文件中的 id 值。程序在加载 spring.xml 时创建 stu 对象,通过反射机制调用无参构造函数,所有要求交给 IoC 容器管理的类必须有无参构造函数。
第三步:
Spring 通过调用每个属性的 setter 方法来完成属性的赋值,因此实体类必须有 setter 方法,否则加载时报错,getter 方法可省略。
2.通过运行时类加载
//1.加载 spring.xml 配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
//2.通过运行时类获取对象
Student stu = applicationContext.getBean(Student.class);
System.out.println(stu);
此方法有一个弊端,当 spring.xml 中配置两个 Student 的 bean 时程序会抛出异常,因为此时两个 bean 都是由 Student 类生成的,IoC 容器无法将两个 bean 都返回,必须指定一个唯一的 bean。
有参构造方法加载
以上是 IoC 容器通过有参构造创建对象的方式,获取对象同样有两种方式可以选择:id 和运行时类。