spring系列

02 Spring IOC

2020-04-26  本文已影响0人  better_future

什么是程序的耦合性?

耦合性(Coupling),也叫耦合度,是对模块间关联程度的度量。耦合的强弱取决于模块间接口的复杂性、调用模块的方式以及通过界面传送数据的多少。模块间的耦合度是指模块之间的依赖关系,包括控制关系、调用关系、数据传递关系。模块间联系越多,其耦合性越强,同时表明其独立性越差( 降低耦合性,可以提高其独立性)。耦合性存在于各个领域,而非软件设计中独有的,但是我们只讨论软件工程中的耦合。

它有如下分类:

(1) 内容耦合。当一个模块直接修改或操作另一个模块的数据时,或一个模块不通过正常入口而转入另一个模块时,这样的耦合被称为内容耦合。内容耦合是最高程度的耦合,应该避免使用之。

(2) 公共耦合。两个或两个以上的模块共同引用一个全局数据项,这种耦合被称为公共耦合。在具有大量公共耦合的结构中,确定究竟是哪个模块给全局变量赋了一个特定的值是十分困难的。

(3) 外部耦合 。一组模块都访问同一全局简单变量而不是同一全局数据结构,而且不是通过参数表传递该全局变量的信息,则称之为外部耦合。

(4) 控制耦合 。一个模块通过接口向另一个模块传递一个控制信号,接受信号的模块根据信号值而进行适当的动作,这种耦合被称为控制耦合。

(5) 标记耦合 。若一个模块 A 通过接口向两个模块 B 和 C 传递一个公共参数,那么称模块 B 和 C 之间存在一个标记耦合。

(6) 数据耦合。模块之间通过参数来传递数据,那么被称为数据耦合。数据耦合是最低的一种耦合形式,系统中一般都存在这种类型的耦合,因为为了完成一些有意义的功能,往往需要将某些模块的输出数据作为另一些模块的输入数据。

(7) 非直接耦合 。两个模块之间没有直接关系,它们之间的联系完全是通过主模块的控制和调用来实现的。

总结:

耦合是影响软件复杂程度和设计质量的一个重要因素,在设计上我们应采用以下原则:如果模块间必须存在耦合,就尽量使用数据耦合,少用控制耦合,限制公共耦合的范围,尽量避免使用内容耦合。

public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = new AccountDaoImpl();
}

上面的代码表示:
业务层调用持久层,并且此时业务层在依赖持久层的接口和实现类。如果此时没有持久层实现类,编译将不能通过。这种编译期依赖关系,应该在我们开发中杜绝。我们需要优化代码解决。

再比如:
早期我们的 JDBC 操作,注册驱动时,我们为什么不使用 DriverManager 的 register 方法,而是采用 Class.forName 的方式?

//1.注册驱动
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");

原因就是:
我们的类依赖了数据库的具体驱动类(MySQL),如果这时候更换了数据库品牌(比如 Oracle),需要修改源码来重新数据库驱动。这显然不是我们想要的。

解决程序耦合的思路

当是我们讲解 jdbc 时,是通过反射来注册驱动的,代码如下:
Class.forName("com.mysql.jdbc.Driver");//此处只是一个字符串

此时的好处是,我们的类中不再依赖具体的驱动类,此时就算删除 mysql 的驱动 jar 包,依然可以编译(运行就不要想了,没有驱动不可能运行成功的)。同时,也产生了一个新的问题,mysql 驱动的全限定类名字符串是在 java 类中写死的,一旦要改还是要修改源码。

解决这个问题也很简单,使用配置文件配置。

工厂模式解耦

在实际开发中我们可以把三层的对象都使用配置文件配置起来,当启动服务器应用加载的时候,让一个类中的方法通过读取配置文件,把这些对象创建出来 并存起来。在接下来的使用的时候,直接拿过来用就好了。那么,这个读取配置文件,创建和获取三层对象的类就是工厂。

控制反转 Inversion Of Control

创建的对象存哪里去呢?

分析:由于我们是很多对象,肯定要找个集合来存。这时候有 Map 和 List 供选择。到底选 Map 还是 List 就看我们有没有查找需求。有查找需求,选 Map。

所以我们的答案就是:在应用加载时,创建一个 Map,用于存放三层对象。我们把这个 map 称之为 容器

那什么是工厂?

工厂就是负责给我们从容器中获取指定对象的类。

这时候我们获取对象的方式发生了改变。
原来:我们在获取对象时,都是采用 new 的方式。是主动的。

image.png
现在:
我们获取对象时,同时跟工厂要,有工厂为我们查找或者创建对象。是被动的。
image.png

这种被动接收的方式获取对象的思想就是控制反转,它是 spring 框架的核心之一。

明确 ioc 的作用:

削减计算机程序的耦合(解除我们代码中的依赖关系)。
首先模拟业务层和持久层的关系


image.png

在业务层中创建了持久层的对象,没有解耦合,有依赖关系

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao = new AccountDaoImpl(); //此处有依赖关系待解决
    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }
}

使用spring容器,创建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">

    <!-- bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中
        id 属性:对象的唯一标识。
        class 属性:指定要创建对象的全限定类名-->
    <!-- 配置 service -->
    <bean id="accountService" class="com.it.service.impl.AccountServiceImpl">
    </bean>
    <!-- 配置 dao -->
    <bean id="accountDao" class="com.it.dao.impl.AccountDaoImpl"></bean>
</beans>

bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中
id 属性:对象的唯一标识。用来获取容器中的对象
class 属性:指定要创建对象的全限定类名-->

public class Test {
    public static void main(String[] args) {
        //使用applicationcontext接口 获取spring 容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        //根据bean的id获取对象
        AccountService accountService = (AccountService) applicationContext.getBean("accountService");

        System.out.println(accountService);

        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
        System.out.println(accountDao);
    }
}

查看ApplicationContext的实现类


image.png

两个基于xml的实现类:
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext

一个基于注解配置的实现类:
AnnotationConfigApplicationContext


image.png

BeanFactory 和 和 ApplicationContext 的区别

BeanFactory 才是 Spring 容器中的顶层接口。
ApplicationContext 是它的子接口。

创建对象的时间点不一样

ApplicationContext:只要一读取配置文件,默认情况下就会创建对象。
BeanFactory:什么使用什么时候创建对象。

ApplicationContext 接口的实现类

ClassPathXmlApplicationContext :它是从类的根路径下加载配置文件 推荐使用这种

FileSystemXmlApplicationContext :它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。

AnnotationConfigApplicationContext:当我们使用注解配置容器对象时,需要使用此类来创建 spring 容器。它用来读取注解。

IOC 中 中 bean 标签 和管理对象细节

bean 标签

作用:
用于配置对象让 spring 来创建的。
默认情况下它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。
属性:
id:给对象在容器中提供一个唯一标识。用于获取对象。
class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。
init-method:指定类中的初始化方法名称。
destroy-method:指定类中销毁方法名称。
scope:指定对象的作用范围:

bean 的作用范围和生命周期

单例对象:scope="singleton"

一个应用只有一个对象的实例。它的作用范围就是整个引用。
生命周期
对象出生:当应用加载,创建容器时,对象就被创建了。
对象活着:只要容器在,对象一直活着。
对象死亡:当应用卸载,销毁容器时,对象就被销毁了。
总结:随容器生或灭

多例对象:scope="prototype"

每次访问对象时,都会重新创建对象实例。
生命周期
对象出生:当使用对象时,创建新的对象实例。
对象活着:只要对象在使用中,就一直活着。
对象死亡:当对象长时间不用时,被 java 的垃圾回收器回收了。

实例化Bean的三种方式

第一种方式:使用默认无参构造函数
在默认情况下:
它会根据默认无参构造函数来创建类对象。如果 bean 中没有默认无参构造函数,将会创建失败。
第二种方式:spring 管理静态工厂的方法创建对象

/**
* 模拟一个静态工厂,创建业务层实现类
*/
public class StaticFactory { 
    public static IAccountService createAccountService(){
            return new AccountServiceImpl();
  }
}
<bean id="accountService"
class="com.itheima.factory.StaticFactory"
factory-method="createAccountService"></bean>

此种方式是:
使用 StaticFactory 类中的静态方法 createAccountService 创建对象,并存入spring 容器。
id 属性:指定 bean 的 id,用于从容器中获取对象
class 属性:指定静态工厂的全限定类名
factory-method 属性:指定生产对象的静态方法

第三种方式:spring 管理实例工厂-使用实例工厂的方法创建对象
/**
* 模拟一个实例工厂,创建业务层实现类
* 此工厂创建对象,必须现有工厂实例对象,再调用方法
*/
public class InstanceFactory {
      public IAccountService createAccountService(){
              return new AccountServiceImpl();
      }
}
<bean id="instancFactory" class="com.itheima.factory.InstanceFactory"></bean>

<bean id="accountService" factory-bean="instancFactory" factory-method="createAccountService"></bean>

此种方式是:
先把工厂的创建交给 spring 来管理。
然后在使用工厂的 bean 来调用里面的方法
factory-bean 属性:用于指定实例工厂 bean 的 id。
factory-method 属性:用于指定实例工厂中创建对象的方法。

spring的依赖注入

依赖注入:Dependency Injection。它是 spring 框架核心 ioc 的具体实现。我们的程序在编写时,通过控制反转,把对象的创建交给了 spring,但是代码中不可能出现没有依赖的情况。

ioc 解耦只是降低他们的依赖关系,但不会消除。例如:我们的业务层仍会调用持久层的方法。

那这种业务层和持久层的依赖关系,在使用 spring 之后,就让 spring 来维护了。
简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。

(一)构造函数注入
public class AccountServiceImpl implements AccountService {

    private String name;
    private Integer age;
    private Date birthday;

    public AccountServiceImpl(String name, Integer age, Date birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }
   
    @Override
    public void saveAccount() {
        System.out.println(name+","+age+","+birthday);
    }
}
<!--构造方法注入-->
<bean id="accountService" class="com.it.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value=" 张三 "></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<bean id="now" class="java.util.Date"></bean>

使用构造函数的方式,给 service 中的属性传值
要求:类中需要提供一个对应参数列表的构造函数。
涉及的标签:constructor-arg
标签属性:
index:指定参数在构造函数参数列表的索引位置
type:指定参数在构造函数中的数据类型
name:指定参数在构造函数中的名称
=======上面三个都是找给谁赋值,下面两个指的是赋什么值的==============
value:它能赋的值是基本数据类型和 String 类型
ref:它能赋的值是其他 bean 类型,也就是说,必须得是在配置文件中配置过的 bean
测试

public class Test {
    public static void main(String[] args) {
        //使用applicationcontext接口 获取spring 容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        //根据bean的id获取对象
        AccountService accountService = (AccountService) applicationContext.getBean("accountService");
        accountService.saveAccount();
    }
}
(二)set方法注入

对所有注入属性,生成set方法

public class AccountServiceImpl implements AccountService {
    private String name;
    private Integer age;
    private Date birthday;
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    @Override
    public void saveAccount() {
        System.out.println(name+","+age+","+birthday);
    }
}
  <!--set方法注入-->
    <bean id="accountService" class="com.it.service.impl.AccountServiceImpl">
        <property name="name" value="test"></property>
        <property name="age" value="21"></property>
        <property name="birthday" ref="now"></property>
    </bean>
    <bean id="now" class="java.util.Date"></bean>

涉及的标签:property
属性:
name:找的是类中 set 方法后面的部分
ref:给属性赋值是其他 bean 类型的
value:给属性赋值是基本数据类型和 string 类型的
实际开发中,此种方式用的较多。

(三)使用 p 名称空间 注入数据(本质还是调用set方法)
public class AccountServiceImpl implements AccountService {

    private String name;
    private Integer age;
    private Date birthday;
    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public void saveAccount() {
        System.out.println(name+","+age+","+birthday);
    }
}

配置p名称空间,在bean.xml头部添加名称空间

xmlns:p="http://www.springframework.org/schema/p"
<bean id="accountService"
          class="com.it.service.impl.AccountServiceImpl"
          p:name="test" p:age="21" p:birthday-ref="now"/>
    <bean id="now" class="java.util.Date"></bean>

注入集合属性

顾名思义,就是给类中的集合成员传值,它用的也是set方法注入的方式,只不过变量的数据类型都是集合。

public class AccountServiceImpl implements AccountService {
    private String[] myStrs;
    private List<String> myList;
    private Set<String> mySet;
    private Map<String ,String> myMap;
    private Properties myProps;

    public void setMyStrs(String[] myStrs) {
        this.myStrs = myStrs;
    }

    public void setMyList(List<String> myList) {
        this.myList = myList;
    }

    public void setMySet(Set<String> mySet) {
        this.mySet = mySet;
    }

    public void setMyMap(Map<String, String> myMap) {
        this.myMap = myMap;
    }

    public void setMyProps(Properties myProps) {
        this.myProps = myProps;
    }

    @Override
    public void saveAccount() {
        System.out.println(Arrays.toString(myStrs));
        System.out.println(myList);
        System.out.println(mySet);
        System.out.println(myMap);
        System.out.println(myProps);
    }
}

配置bean

  <bean id="accountService" class="com.it.service.impl.AccountServiceImpl">
        <!--注入数组-->
        <property name="myStrs">
            <set>
                <value>AAAA</value>
                <value>BBBB</value>
                <value>CCCC</value>
            </set>
        </property>
        <!--注入list集合数据-->
        <property name="myList">
            <array>
                <value>AAA</value>
                <value>BBB</value>
                <value>CCC</value>
            </array>
        </property>
 <!--注入set集合数据-->
        <property name="mySet">
            <list>
                <value>AAA</value>
                <value>BBB</value>
                <value>CCC</value>
            </list>
        </property>
        <!--注入map-->
        <property name="myMap">
            <props>
                <prop key="testA">aaa</prop>
                <prop key="testB">bbb</prop>
            </props>
        </property>
        <!-- 注入 properties 数据 -->
        <property name="myProps">
            <map>
                <entry key="testA" value="aaa"></entry>
                <entry key="testB">
                    <value>bbb</value>
                </entry>
            </map>
        </property>
    </bean>
上一篇下一篇

猜你喜欢

热点阅读