Spring IOC 容器详细讲解及使用


一、Spring IOC 容器介绍

1、IOC 思想

IOC (Inversion of Control) 是指在程序开发中,对象实例的创建不再由调用者管理,而是由 Spring 容器创建。Spring 容器会负责控制程序之间的关系,而不是由程序代码直接控制,因此,控制权由程序代码转移到了 Spring 容器中,控制权发生了反转,这就是 Spring 的IOC 思想。

2、IOC 容器概念

IOC 容器就是具有依赖注入功能的容器,IOC 容器负责实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。应用程序无需直接在代码中 new 相关的对象,应用程序由 IOC 容器进行组装。在 Spring 中 BeanFactory 是 IOC 容器的实际代表者。

3、Bean 的概念

在 Spring 中,被 Spring 容器所管理的对象称之为”Bean”对象。一个 Spring 的 Bean 对象可以是任何形式的 POJO。

二、 Spring IOC 容器类型

Spring 提供了两种 IoC 容器,分别为 BeanFactoryApplicationConte

1、BeanFactory

BeanFactory 是基础类型的 IoC 容器。
它由 org.springframework.beans.facytory.BeanFactory 接口定义,并提供了完整的 IoC服务支持。简单来说,BeanFactory 就是一个管理 Bean 的工厂,它主要负责初始化各种Bean,并调用它们的生命周期方法。

2、ApplicationContext

ApplicationContext 是 BeanFactory 的子接口,也被称为应用上下文。该接口的全路径为 org.springframework.context.ApplicationContext,它不仅提供了 BeanFactory 的所有功能,还添加了对国际化、资源访问、事件传播等方面的良好支持。

ApplicationContext 接口有两个常用的实现类:

2.1、 ClassPathXmlApplicationContext

该 类 从 类 路 径 ClassPath 中 寻 找 指 定 的 XML 配 置 文 件 , 找 到 并 装 载 完 成ApplicationContext 的实例化工作。

ApplicationContext applicationContext = new FileSystemXmlApplicationContext(String configLocation)

它与 ClassPathXmlApplicationContext 的区别是:在读取 Spring 的配置文件时,
FileSystemXmlApplicationContext 不再从类路径中读取配置文件,而是通过参数指定配置文件的位置,它可以获取类路径之外的资源,如“F:/workspaces/applicationContext.xml”;

三、 Spring IOC 容器的使用

1、搭建环境

1.1、 创建项目

在这里插入图片描述

1.2、 添加 jar 包

在这里插入图片描述

1.3、 添加 Spring 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

2、通过 IOC 容器管理 Bean 对象

2.1、 创建 UsersService 接口与实现类

public interface UsersService {
   
    void addUsers();
}

public class UsersServiceImpl implements UsersService {
   
    @Override
    public void addUsers() {
   
        System.out.println("UsersService addUsers .....");
    }
}

2.2、 修改配置文件

    <bean id="usersService" class="com.bjsxt.service.impl.UsersServiceImpl"/>

2.3、 获取 IOC 容器中的对象

public class UsersServiceTest {
   
    public static void main(String[] args) {
   
        //启动Spring IOC容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //从IOC容器中获取
        UsersService usersService = (UsersService)applicationContext.getBean("usersService");
        usersService.addUsers
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值