任务描述:
本关任务:根据要求使用 Spring 容器获取bean
的信息。
相关知识:
Spring 容器是 Spring 框架的核心。容器将创建对象,把它们连接在一起,配置它们,并管理他们的整个生命周期从创建到销毁。
Spring 容器使用依赖注入( DI )来管理组成一个应用程序的组件,这些对象被称为 Spring Beans ,我们将在之后的实训中进行讨论。
IOC 容器读取 Bean 配置文件创建 Bean 实例之前,必须对它进行实例化(加载启动),这样才可以从容器中获取 Bean 的实例并使用。 IOC 容器的设计主要是基于以下两个接口:
-
BeanFactory
-
ApplicationContext
为了完成本关任务,你需要掌握:如何使用 Spring 容器中的一些常用方法。
BeanFactory 容器:
BeanFactory 是 IOC 容器所定义的最底层接口,面向 Spring 本身,它提供了 IOC 最底层的设计,因此我们来看看该类中提供的几个主要方法:
-
boolean containsBean(String name)
:判断容器是否包含id
为name
的Bean
实例。 -
Object getBean(String name)
:获取容器中id
为name
的Bean
实例。 -
<T> getBean(Class<T> class)
:获取容器中属于class
类型的唯一的Bean
实例。 -
<T> T getBean(String name,Class class)
:获取容器中id
为name
,并且类型为class
的Bean
。 -
Class <?> getType(String name)
:获取容器中指定Bean
实例的类型。
这是IOC
最底层的设计,所有关于IOC
容器都将会遵守它所定义的方法。
ApplicationContext 容器:
ApplicationContext
是 BeanFactory
的子接口之一,也是其最高级接口之一,并对 BeanFactory
功能做了许多的扩展,所以在绝大部分的工作场景下,都会使用 ApplicationContext
作为 IOC
容器。
两个实现类:
ClassPathXmlApplicationContext
:加载类路径下Spring
的配置文件-
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
FileSystemXmlApplicationContext
:加载本地磁盘下Spring
的配置文件-
String path="文件绝对路径"; ApplicationContext applicationContext = new FileSystemXmlApplicationContext(path);
编程要求:
在右侧编辑器补充代码,要求使用ApplicationContext
容器完成如下操作:
-
判断容器是否包含
id
为Student
和helloworld
的bean
实例,并输出判断结果; -
分别使用三种方法获取
bean
实例,并调用实例中toString()
方法做为输出内容。(id
为helloworld
,class
为HelloWorld.class
)
注意:Spring 配置文件名称为applicationContext2.xml
。
参考答案:
MainApp.java
package step2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import step2.HelloWorld;
public class MainApp {
public static void fun() {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext2.xml");
boolean s = app.containsBean("Student");
System.out.println(s);
boolean h = app.containsBean("helloworld");
System.out.println(h);
HelloWorld helloworld1 = (HelloWorld)app.getBean("helloworld");
System.out.println(helloworld1.toString());
HelloWorld helloworld2 = app.getBean("helloworld",HelloWorld.class);
System.out.println(helloworld2.toString());
Object helloworld3 = app.getBean("helloworld");
System.out.println(helloworld3.toString());
}