上一篇:Spring框架的入门介绍
文章目录
1、程序的耦合和解耦
1.1、什么是程序的耦合?
耦合性(Coupling),也叫耦合度,是对模块间关联程度的度量。耦合的强弱取决于模块间接口的复杂性、调用模块的方式以及通过界面传送数据的多少。模块间的耦合度是指模块之间的依赖关系,包括控制关系、调用关系、数据传递关系。模块间联系越多,其耦合性越强,同时表明其独立性越差( 降低耦合性,可以提高其独立性)。耦合性存在于各个领域,而非软件设计中独有的,但是我们只讨论软件工程中的耦合。
在软件工程中,耦合指的就是就是对象之间的依赖性。对象之间的耦合越高,维护成本越高。因此对象的设计应使类和构件之间的耦合最小。软件设计中通常用耦合度和内聚度作为衡量模块独立程度的标准。
划分模块的一个准则就是高内聚低耦合。
耦合的分类:
(1)内容耦合。当一个模块直接修改或操作另一个模块的数据时,或一个模块不通过正常入口而转入另一个模块时,这样的耦合被称为内容耦合。内容耦合是最高程度的耦合,应该避免使用之。
(2)公共耦合。两个或两个以上的模块共同引用一个全局数据项,这种耦合被称为公共耦合。在具有大量公共耦合的结构中,确定究竟是哪个模块给全局变量赋了一个特定的值是十分困难的。
(3)外部耦合 。一组模块都访问同一全局简单变量而不是同一全局数据结构,而且不是通过参数表传递该全局变量的信息,则称之为外部耦合。
(4)控制耦合 。一个模块通过接口向另一个模块传递一个控制信号,接受信号的模块根据信号值而进行适当的动作,这种耦合被称为控制耦合。
(5)标记耦合 。若一个模块 A 通过接口向两个模块 B 和 C 传递一个公共参数,那么称模块 B 和 C 之间存在一个标记耦合。
(6)数据耦合。模块之间通过参数来传递数据,那么被称为数据耦合。数据耦合是最低的一种耦合形式,系统中一般都存在这种类型的耦合,因为为了完成一些有意义的功能,往往需要将某些模块的输出数据作为另一些模块的输入数据。
(7)非直接耦合 。两个模块之间没有直接关系,它们之间的联系完全是通过主模块的控制和调用来实现的。
耦合是影响软件复杂程度和设计质量的一个重要因素,在设计上我们应采用以下原则:如果模块间必须存在耦合,就尽量使用数据耦合,少用控制耦合,限制公共耦合的范围,尽量避免使用内容耦合。
内聚和耦合:
内聚标志一个模块内各个元素彼此结合的紧密程度,它是信息隐蔽和局部化概念的自然扩展。内聚是从功能角度来度量模块内的联系,一个好的内聚模块应当恰好做一件事。它描述的是模块内的功能联系。
耦合是软件结构中各模块之间相互连接的一种度量,耦合强弱取决于模块间接口的复杂程度、进入或访问一个模块的点以及通过接口的数据。
程序讲究的是低耦合,高内聚。就是同一个模块内的各个元素之间要高度紧密,但是各个模块之间的相互依存度却要不那么紧密。内聚和耦合是密切相关的,同其他模块存在高耦合的模块意味着低内聚,而高内聚的模块意味着该模块同其他模块之间是低耦合。在进行软件设计时,应力争做到高内聚,低耦合。
1.2、工厂模式解耦
简单来说,在实际开发中我们可以把三层(持久层、业务层、表现层)的对象都使用配置文件配置起来,当启动服务器应用加载的时候,让一个类中的方法通过读取配置文件,把这些对象创建出来 并存起来。在接下来的使用的时候,直接拿过来用就好了。那么,这个读取配置文件,创建和获取三层对象的类就是工厂。
对象保存在哪里?
由于我们有很多对象,肯定要找个集合来存。这时候有 Map 和 List 供选择。到底选 Map 还是 List 就看我们有没有查找需求。有查找需求,选 Map。在应用加载时,创建一个 Map,用于存放三层对象。我们把这个 map 称之为容器。
什么是工厂?
简单来说, 工厂就是负责给我们从容器中获取指定对象的类。使用工厂后,我们获取对象的方式就发生了变化。原来我们在获取对象时,都是采用new
的方式,这是主动去获取对象。而现在我们获取对象时,要向工厂获取,右工厂为我们查找或创建对象,这是被动去获取对象。
这种被动的方式获取对象的思想就是控制反转(IOC),即把创建对象的控制权交给工厂。而控制反转(IOC)的作用就是削减计算机程序的耦合,降低代码中的依赖关系。
工厂模式示例
(1)首先创建一个配置文件(bean.properties)来配置 service 和 dao 的全路径类名,配置文件可以是 xml 也可以是 properties。
accountService=com.atlantis.service.impl.AccountServiceImpl
accountDao=com.atlantis.dao.impl.AccountDaoImpl
(2)通过读取配置文件中的配置内容,反射来创建对象。
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class BeanFactory {
//定义一个Properties对象
private static Properties props;
//定义一个Map,用于存放我们要创建的对象。我们把它称之为容器
private static Map<String,Object> beans;
//使用静态代码块为Properties对象赋值
static {
try {
//实例化对象
props = new Properties();
//获取properties文件的流对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
//实例化容器
beans = new HashMap<String,Object>();
//取出配置文件中所有的Key
Enumeration keys = props.keys();
//遍历枚举
while (keys.hasMoreElements()){
//取出每个Key
String key = keys.nextElement().toString();
//根据key获取value
String beanPath = props.getProperty(key);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key和value存入容器中
beans.put(key,value);
}
}catch(Exception e){
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
/**
* 根据bean的名称获取对象
*/
public static Object getBean(String beanName){
return beans.get(beanName);
}
}
2、使用Spring的IOC解决程序耦合
下面使用的是Spring5.0.2版本,要求 JDK 版本8及以上,同时 Tomcat 版本要求8.5及以上。
(1)创建业务层和持久层的接口和实现类
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao = new AccountDaoImpl();
public void saveAccount() {
accountDao.saveAccount();
}
}
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements AccountDao {
public void saveAccount() {
System.out.println("保存了账户");
}
}
(2)导入Spring核心jar包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.atlantis</groupId>
<artifactId>Spring</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
</project>
(3)创建bean.xml配置文件,让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">
<!-- 把创建对象的控制权交给Spring -->
<!-- 配置Service -->
<bean id="accountService" class="com.atlantis.service.impl.AccountServiceImpl" />
<!-- 配置Dao -->
<bean id="accountDao" class="com.atlantis.dao.impl.AccountDaoImpl" />
</beans>
(4)测试是否配置成功
import com.atlantis.dao.AccountDao;
import com.atlantis.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 模拟一个表现层,用于调用业务层
*/
public class Client {
/**
* 获取Spring的IOC核心容器,并根据id获取对象
*/
public static void main(String[] args) {
// 1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.根据bean的id获取对象
// 2.1.第一种方式
AccountService accountService = (AccountService) ac.getBean("accountService");
System.out.println(accountService);
// 2.2.第二种方式
AccountDao accountDao = ac.getBean("accountDao",AccountDao.class);
System.out.println(accountDao);
}
}
3、Spring中工厂的类结构
BeanFactory和ApplicationContext的区别
BeanFactory 是 Spring 容器中的顶层接口,而 ApplicationContext 是它的子接口。
两者区别在于创建对象的时间点不一样。ApplicationContext:只要一读取配置文件,默认情况下就会立即创建对象。BeanFactory :什么时候使用就什么时候创建对象。
ApplicationContext接口的三个常用实现类
ApplicationContext接口的实现类 | 描述 |
---|---|
ClassPathXmlApplicationContext | 从类的根路径下加载配置文件(推荐使用这种) |
FileSystemXmlApplicationContext | 从磁盘路径上加载配置文件(必须有访问权限),配置文件可以在磁盘的任意位置 |
AnnotationConfigApplicationContext | 使用注解配置容器对象时,需要使用此类来创建 spring 容器,它用来读取注解 |
4、IOC中的bean标签
4.1、bean标签
bean 标签的作用就是用于配置对象让 Spring 来创建的。默认情况下它调用的是类的无参构造函数,如果没有无参构造函数则不能创建对象。
bean标签中的属性 | 描述 |
---|---|
id | 给对象在容器中提供一个唯一标识。用于获取对象 |
class | 指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数 |
scope | 指定对象的作用范围 |
init-method | 指定类中的初始化方法名称 |
destroy-method | 指定类中销毁方法名称 |
scope属性 | 描述 |
---|---|
singleton | 默认值,单例模式 |
prototype | 多例模式 |
request | WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中 |
session | WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中 |
global session | WEB 项目中,应用在 Portlet 集群环境。如果没有 Portlet 集群环境,那么 globalSession 相当于 session |
4.2、bean作用范围的生命周期
(1)单例对象:scope="singleton"
一个应用只有一个对象的示例。它的作用范围就是整个引用。
当程序加载,创建容器时,对象就被创建了。只有容器存在,对象就一直存在。当程序和容器被销毁时,对象就被销毁了。
(2)多例对象:scope="prototype"
每次访问对象时,都会重新创建对象实例。
当使用对象时,才会创建新的对象实例。只要对象在使用中,就一直存在。当对象长时间不使用时,就会被 Java 的垃圾回收机制回收了。
4.3、创建bean的三种方式
(1)使用默认无参构造函数创建对象
在 Spring 的配置文件中使用 bean 标签,配置 id 和 class 属性后,且没有其他属性和标签时,就会去寻找 class 属性指定类的默认无参构造函数 创建 bean 对象。如果类中没有默认构造函数,则对象无法创建。
<bean id="accountService" class="com.atlantis.service.impl.AccountServiceImpl" />
(2)Spring管理静态工厂,使用静态工厂的方法创建对象
首先模拟一个静态工厂,创建业务层的实现类。
public class StaticFactory {
public static IAccountService createAccountService(){
return new AccountServiceImpl();
}
}
<bean id="accountService" class="com.atlantis.factory.StaticFactory" factory-method="createAccountService"></bean>
这种方法就是使用 StaticFactory 类中的静态方法 createAccountService 来创建对象,并存入 Spring 容器中。
属性 | 描述 |
---|---|
id | 用于指定实例工厂 bean 的 id |
class | 指定静态工厂的全限定类名 |
factory-method | 指定生产对象的静态方法 |
(3)Spring管理实例工厂,使用实例工厂的方法创建对象
首先模拟一个实例工厂,创建业务层的实现类。此工厂创建对象,必须先有工厂实例对象,再调用方法。
public class InstanceFactory {
public IAccountService createAccountService(){
return new AccountServiceImpl();
}
}
<bean id="instancFactory" class="com.atlantis.factory.InstanceFactory"></bean>
<bean id="accountService" factory-bean="instancFactory" factory-method="createAccountService"></bean>
这种方法就是先把工厂的创建交给 Spring 来管理,然后在使用工厂的 bean 来调用里面的方法。
属性 | 描述 |
---|---|
factory-bean | 用于指定实例工厂 bean 的 id |
factory-method | 用于指定实例工厂中创建对象的方法 |
5、Spring的依赖注入
依赖注入:Dependency Injection。它是 Spring框架核心 IOC 的具体实现。
我们在编写程序时,通过控制反转,把对象的创建交给了 Spring,但是代码中不可能出现没有依赖的情况。IOC 解耦只是降低它们的依赖关系,但不会消除。例如:我们的业务层仍会调用持久层的方法。那这种业务层和持久层的依赖关系,在使用 Spring之后,就让 Spring来维护了。
简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。
5.1、构造函数注入
顾名思义,就是使用类中的构造函数,给成员变量赋值。注意,赋值的操作不是我们自己做的,而是通过配置的方式,让 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.atlantis.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="atlantis"></constructor-arg>
<constructor-arg name="age" value="23"></constructor-arg>
<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<bean id="now" class="java.util.Date"></bean>
constructor-arg 标签的属性 | 描述 |
---|---|
index | 指定参数在构造函数参数列表的索引位置 |
type | 指定参数在构造函数中的数据类型 |
name | 指定参数在构造函数中的名称 |
value | 能赋的值是基本数据类型和 String 类型 |
index | 能赋的值是其他 bean 类型,也就是说,必须得是在配置文件中配置过的 bean |
5.2、set方法注入
顾名思义,就是在类中提供需要注入成员的 set 方法,并通过配置文件给 bean 中的属性传值。在实际开发中,此种方式用的比较多。具体代码如下:
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);
}
}
<bean id="accountService" class="com.atlantis.service.impl.AccountServiceImpl">
<property name="name" value="atlantis"></property>
<property name="age" value="23"></property>
<property name="birthday" ref="now"></property>
</bean>
<bean id="now" class="java.util.Date"></bean>
5.3、使用 p 名称空间注入数据
这种方法本质还是调用类中的 set 方法来实现注入功能,通过在 xml 中导入 p 名称空间,使用p:propertyName
来注入数据。
Java 类代码同【5.2、set方法注入】案例中一致,只对配置文件修改:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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 id="accountService" class="com.atlantis.service.impl.AccountServiceImpl" p:name="atlantis" p:age="23" p:birthday-ref="now"/>
</beans>
<bean id="now" class="java.util.Date"></bean>
5.4、集合属性注入
顾名思义,就是给类中的集合成员传值,它用的也是 set 方法注入的方式,只不过变量的数据类型都是集合。我们这里介绍注入数组,List,Set,Map,Properties。具体代码如下:
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 id="accountService" class="com.atlantis.service.impl.AccountServiceImpl">
<!-- 在注入集合数据时,只要结构相同,标签可以互换 -->
<!-- 给数组注入数据 -->
<property name="myStrs">
<set>
<value>AAA</value>
<value>BBB</value>
<value>CCC</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>
后面讲解 Spring 框架的 IOC 注解配置:https://blog.csdn.net/q961250375/article/details/102883435。