Educoder Spring入门 第二关:Spring IOC 容器

28 篇文章 9 订阅

任务描述:

本关任务:根据要求使用 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):判断容器是否包含idnameBean实例。

  • Object getBean(String name):获取容器中idnameBean实例。

  • <T> getBean(Class<T> class):获取容器中属于class类型的唯一的Bean实例。

  • <T> T getBean(String name,Class class):获取容器中idname,并且类型为classBean

  • Class <?> getType(String name):获取容器中指定Bean实例的类型。

这是IOC最底层的设计,所有关于IOC容器都将会遵守它所定义的方法。

ApplicationContext 容器:

ApplicationContextBeanFactory 的子接口之一,也是其最高级接口之一,并对 BeanFactory 功能做了许多的扩展,所以在绝大部分的工作场景下,都会使用 ApplicationContext 作为 IOC 容器。

896c26af76404f00be7c38e0e703583f.png

两个实现类:

  • ClassPathXmlApplicationContext:加载类路径下Spring的配置文件
  • ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  • FileSystemXmlApplicationContext:加载本地磁盘下Spring的配置文件
  • String path="文件绝对路径";
    ApplicationContext applicationContext = new FileSystemXmlApplicationContext(path);

编程要求:

在右侧编辑器补充代码,要求使用ApplicationContext容器完成如下操作:

  1. 判断容器是否包含idStudenthelloworldbean实例,并输出判断结果;

  2. 分别使用三种方法获取bean实例,并调用实例中toString()方法做为输出内容。(idhelloworldclassHelloWorld.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());
	}

 7aa88c29444a4cc49e3573d1d1b56d84.png

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

于建章

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值