构造器实例化
构造器实例化是指Spring容器通过Bean对应类中默认的无参构造方法来实例化Bean。下面通过一个案例来演示Spring容器是如何通过构造器来实例化Bean的。
(1)在Eclipse中,创建一个名为chapter02的Web项目,在该项目的lib目录中加入Spring支持和依赖的JAR包。
(2)在chapter02项目的src目录下,创建一个com.itheima.instance.constructor包,在该包中创建Bean1类,如文件1所示。
文件1 Bean1.java
1 package com.itheima.instance.constructor;
2 public class Bean1 {
3 }
(3)在com.itheima.instance.constructor包中,创建Spring的配置文件beans1.xml,在配置文件中定义一个id为bean1的Bean,并通过class属性指定其对应的实现类为Bean1,如文件2所示。
文件2 beans1.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
6 <bean id="bean1" class="com.itheima.instance.constructor.Bean1" />
7 </beans>
(4)在com.itheima.instance.constructor包中,创建测试类InstanceTest1,来测试构造器是否能实例化Bean,编辑后如文件3所示。
文件3 InstanceTest1.java
1 package com.itheima.instance.constructor;
2 import org.springframework.context.ApplicationContext;
3 import
4 org.springframework.context.support.ClassPathXmlApplicationContext;
5 public class InstanceTest1 {
6 public static void main(String[] args) {
7 // 定义配置文件路径
8 String xmlPath = "com/itheima/instance/constructor/beans1.xml";
9 // ApplicationContext在加载配置文件时,对Bean进行实例化
10 ApplicationContext applicationContext =
11 new ClassPathXmlApplicationContext(xmlPath);
12 Bean1 bean = (Bean1) applicationContext.getBean("bean1");
13 System.out.println(bean);
14 }
15 }
在文件2-3中,首先定义了配置文件的路径,然后Spring容器ApplicationContext会加载配置文件。在加载时,Spring容器会通过id为bean1的实现类Bean1中默认的无参构造方法对Bean进行实例化。执行程序后,控制台的输出结果如图1所示。
图1 运行结果
从图1可以看出,Spring容器已经成功实例化了Bean1,并输出了结果。
为了方便读者的学习,本章中的所有配置文件和类文件(包括测试类)都根据知识点放置在同一个包中。在实际开发中,为了方便管理和维护,建议将这些文件根据类别放置在不同目录中。