Spring中IoC的简单学习

Spring中IoC的简单学习

又是书接上文工厂模式中存在的问题,上文中我举例了

这两种截然不同的创建对象的方式

后者:

graph LR a[程序]-->b[资源] a[程序]-->c[资源] a[程序]-->d[资源] e[传统模式下有程序自身控制资源]

前者:

graph LR b[工厂]-->|提供资源|a[程序] b[工厂]-->|控制资源|c[资源] b[工厂]-->|控制资源|d[资源] b[工厂]-->|控制资源|e[资源] g[工厂模式下程序对资源的控制权交给了工厂,由工厂对程序提供资源]

通过工厂来建立程序和各资源的联系,将控制权由程序本身转移给工厂,这就是“控制反转(IoC)”。把创建对象的权利交给框架。它包括依赖注入(DI)和依赖查找(DL)。这么做的好处就是降低程序间的依赖关系,也就是削减程序耦合。

在实际的开放过程中,我们可以通过自己编写工厂模式来实现降低耦合,但是如果这样会消耗更多的精力,所以我们完全把这部分的内容都交给了Spring框架,让框架来替我们完成这部分的内容。

示例如下:

打开pom.xml,导入spring依赖,添加如下内容

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>

在resources文件夹下新建一个Bean.xml(名字可以随意)的配置文件

<?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">
    <!--把对象的创建交给spring来管理-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>

    <bean id="accountMapper" class="com.itheima.mapper.impl.AccountMapperImpl"></bean>

</beans>

最后便可以用spring的IoC容器,并根据id获取对象

package com.itheima.ui;

import com.itheima.mapper.iAccountMapper;
import com.itheima.service.iAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Author:Zzq
 * @Description:模拟一个表现层,用于调用业务
 * @Date:2020/6/13
 * @Time:22:28
 */
public class Client {

    /**
     * 获取spring的IoC核心容器,并根据id获取对象
     * @param args
     */
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象
        iAccountService as = (iAccountService)ac.getBean("accountService");
        iAccountMapper adMp = ac.getBean("accountMapper" , iAccountMapper.class);

        System.out.println(as);
        System.out.println(adMp);
    }
}

运行结果如下

可以看到,两个不同的对象已经有beanFactor生产出来了,有了Spring框架,我们就能够将工厂部分完全交给框架,我们本身只用关心业务代码的编写,为我们节省时间和精力。

原文地址:https://www.cnblogs.com/zzzqi/p/13139898.html