【Spring】之SpringIOC解决程序耦合-03

1 使用 spring 中的 IOC 解决程序耦合

1.1 Spring中的IOC前期准备

1.1.1 创建Maven工程

在这里插入图片描述

1.1.2 pom.xml引入Spring的开发包

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

1.1.3 创建业务层接口和实现类

AccountService.java中加入

package com.spg.service;

/**
 * 账户业务层的接口
 */
public interface AccountService {

    /**
     * 模拟保存账户
     */
    void saveAccount();
}

AccountServiceImpl.java中加入

package com.spg.service.impl;

import com.spg.dao.AccountDao;
import com.spg.dao.impl.AccountDaoImpl;
import com.spg.service.AccountService;

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao = new AccountDaoImpl();

    public void  saveAccount(){
        accountDao.saveAccount();
    }
}

1.1.4 创建持久层接口和实现类

AccountDao.java中加入

package com.spg.dao;

/**
 * 账户的持久层接口
 */
public interface AccountDao {

    /**
     * 模拟保存账户
     */
    void saveAccount();
}

AccountDaoImpl.java中加入

package com.spg.dao.impl;

import com.spg.dao.AccountDao;

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements AccountDao {

    public  void saveAccount(){
        System.out.println("保存了账户");
    }
}

项目工程结构图如下:
在这里插入图片描述

1.2 Spring基于XML的配置

1.2.1 在resources文件夹中创建bean.xml

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 属性:指定要创建对象的全限定类名
     -->

    <!-- 把对象的创建交给spring来管理-->
    <!-- 配置 dao -->
    <bean id="accountDao" class="com.spg.dao.impl.AccountDaoImpl"/>

    <!-- 配置 service -->
    <bean id="accountService" class="com.spg.service.impl.AccountServiceImpl"/>

</beans>

1.2.2 测试配置是否成功

创建Client.java

package com.spg.ui;

import com.spg.dao.AccountDao;
import com.spg.service.AccountService;
import com.spg.service.impl.AccountServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 模拟一个表现层,用于调用业务层
 */
public class Client {
    /**
     * 获取Spring的Ioc核心容器并根据id获取对象
     * @param args
     */
    public static void main(String[] args) {
        // 1. 获取核心容器对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        // 2.根据id获取Bean对象
        AccountService accountService = (AccountService) applicationContext.getBean("accountService");
        AccountDao accountDao = applicationContext.getBean("accountDao",AccountDao.class);

        System.out.println(accountService);
        System.out.println(accountDao);
    }
}

测试结果:
在这里插入图片描述

1.3 ApplicationContext接口的实现类

ClassPathXmlApplicationContext:它可以加载类路径下的配置文件,要求配置文件必须在类路径下。(更常用)

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");

FileSystemXmlApplicationContext:它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。(必须有访问权限)。

ApplicationContext applicationContext = new FileSystemXmlApplicationContext("E:/Users/IdeaProjects/spring_day01_eesy_03spring/src/main/resources/bean.xml");

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

1.4 BeanFactory 和 ApplicationContext 的区别

(1)ApplicationContext:单例对象适用。 它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说,只要一读取玩配置文件马上就创建配置文件中配置的对象。
AccountServiceImpl.java中加入

 private AccountServiceImpl(){
        System.out.println("对象创建了...");
 }

设置断点,Debug运行Client.java
在这里插入图片描述
(2)BeanFactory: 多例对象适用。它在构建核心容器时,创建对象的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象。

Client.java中修改为:

package com.spg.ui;

import com.spg.dao.AccountDao;
import com.spg.service.AccountService;
import com.spg.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 * 模拟一个表现层,用于调用业务层
 */
public class Client {
    /**
     * 获取Spring的Ioc核心容器并根据id获取对象
     * 核心容器的两个接口引发出的问题:
     *   ApplicationContext:
     *  	它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说,只要一读取玩配置文件马上就创建配置文件中配置的对象。
     *   BeanFactory:
     *      它在构建核心容器时,创建对象的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象。
     * @param args
     */
    public static void main(String[] args) {
        // ----------------BeanFactory----------------
        Resource resource = new ClassPathResource("bean.xml");
        BeanFactory beanFactory = new XmlBeanFactory(resource);
        AccountService accountService = (AccountService) beanFactory.getBean("accountService");
        System.out.println(accountService);

    }

设置断点,Debug运行Client.java
在这里插入图片描述
在这里插入图片描述

Tips:
BeanFactory 才是 Spring 容器中的顶层接口。
ApplicationContext 是它的子接口。
BeanFactoryApplicationContext 的区别:
(1)创建对象的时间点不一样。
(2)ApplicationContext:只要一读取配置文件,默认情况下就会创建对象。
(3)BeanFactory:什么使用什么时候创建对象。

1.5 SpringIOC 中 bean 标签

1.5.1 bean 标签

(1)作用:

  • 用于配置对象让 spring 来创建的。
  • 默认情况下它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。

(2)属性:

  • id: 给对象在容器中提供一个唯一标识。用于获取对象。
  • class: 指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。
  • scope: 指定对象的作用范围。
  • singleton默认值,单例的.
    • prototype:多例的.
    • request :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中.
    • session:WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中.
    • global session:WEB 项目中,应用在 Portlet 环境.如果没有 Portlet 环境那么global session 相当于 session.
  • init-method: 指定类中的初始化方法名称。
  • destroy-method: 指定类中销毁方法名称。

1.5.2 bean 的作用范围和生命周期

(1)单例对象: scope="singleton"

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

(2)多例对象: scope="prototype"

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

1.5.3 创建bean的三种方式

创建Maven项目工程:
在这里插入图片描述
pom.xml文件引入spring依赖

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

(1)第一种方式:使用默认无参构造函数创建: 在spring的配置文件中使用bean标签,配以idclass属性,且没有其它属性和标签时,采用默认构造函数创建bean的对象。如果类中没有默认构造函数,则对象无法创建。

/**
 * 创建业务层实现类
 */
public class AccountServiceImpl implements AccountService {
    public AccountServiceImpl(){
        System.out.println("对象创建了...");
    }
}
<!--在默认情况下:
		它会根据默认无参构造函数来创建类对象。如果 bean 中没有默认无参构造函数,将会创建失败。
-->
<bean id="accountService" class="com.spg.service.impl.AccountServiceImpl"/>

(2)第二种方式: spring 管理静态工厂——使用静态工厂的方法创建对象

/**
* 模拟一个静态工厂,创建业务层实现类
*/
public class StaticFactory {
	public static IAccountService createAccountService(){
		return new AccountServiceImpl();
	}
}
<!-- 此种方式是:
		使用 StaticFactory 类中的静态方法 createAccountService 创建对象,并存入 spring 容器
			id 属性:指定 bean 的 id,用于从容器中获取
			class 属性:指定静态工厂的全限定类名
			factory-method 属性:指定生产对象的静态方法
-->
<bean id="accountService" class="com.spg.factory.StaticFactory" factory-method="createAccountService"/>

(3)第三种方式: spring 管理实例工厂———使用实例工厂的方法创建对象:

/**
* 模拟一个实例工厂,创建业务层实现类
* 此工厂创建对象,必须现有工厂实例对象,再调用方法
*/
public class InstanceFactory {
	public AccountService getAccountService(){
		return new AccountServiceImpl();
	}
}
<!-- 此种方式是:
		先把工厂的创建交给 spring 来管理。 在使用工厂的 bean 来调用里面的方法
			factory-bean 属性:用于指定实例工厂 bean 的 id。
			factory-method 属性:用于指定实例工厂中创建对象的方法。
-->
<bean id="instancFactory" class="com.spg.factory.InstanceFactory"/>
<bean id="accountService" factory-bean="instancFactory" factory-method="getAccountService"/>

1.6 Spring的依赖注入

1.6.1 依赖注入的概念

       依赖注入: Dependency Injection。 它是 spring 框架核心 ioc 的具体实现。
       我们的程序在编写时, 通过控制反转, 把对象的创建交给了 spring,但是代码中不可能出现没有依赖的情况。ioc 解耦只是降低他们的依赖关系,但不会消除。 例如:我们的业务层仍会调用持久层的方法。
       那这种业务层和持久层的依赖关系, 在使用 spring 之后, 就让 spring 来维护了。
       简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。

1.6.2 构造函数注入

创建Maven项目工程:
在这里插入图片描述
pom.xml文件引入spring依赖

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

顾名思义,就是使用类中的构造函数,给成员变量赋值。注意,赋值的操作不是我们自己做的,而是通过配置
的方式,让 spring 框架来为我们注入。具体代码如下:
Java类代码:

package com.spg.entity;

import java.util.Date;

/**
 * 账户的业务层实现类
 */
public class User {
    // 如果是经常变化的数据,并不适用于注入的方式
    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;
    }

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

配置文件代码:

<!-- 使用构造函数的方式,给 service 中的属性传值
	要求:类中需要提供一个对应参数列表的构造函数。
	使用的标签:constructor-arg
	标签出现的位置:bean标签的内部
	constructor-arg标签属性:
		index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值。索引的位置是从0开始
		type:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型
		name:用于指定给构造函数中指定名称的参数赋值
		==============上面三个都是找给谁赋值,下面两个指的是赋什么值的==============
		value:它能赋的值是基本数据类型和 String 类型
		ref:它能赋的值是其他 bean 类型,也就是说,必须得是在配置文件中配置过的 bean
-->
<bean id="user" class="com.spg.entity.User">
	<constructor-arg name="name" value="张三"/>
	<constructor-arg name="age" value="18"/>
	<constructor-arg name="birthday" ref="now"/>
</bean>
<bean id="now" class="java.util.Date"/>

1.6.3 set 方法注入

顾名思义,就是在类中提供需要注入成员的 set 方法。具体代码如下:
Java类代码:

public class User {
	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 toString() {
		System.out.println(name+","+age+","+birthday);
	}
}

配置文件代码:

<!-- 通过配置文件给 bean 中的属性传值:使用 set 方法的方式
	使用的标签:property
    出现的位置:bean标签的内部
	property标签的属性:
		name:找的是类中 set 方法后面的部分
		ref:给属性赋值是其他 bean 类型的
		value:给属性赋值是基本数据类型和 string 类型的
	优势:创建对象时没有明确的限制,可以直接使用默认构造函数
    弊端:如果有某个成员必须有值,则获取对象是有可能set方法没有执行
	实际开发中,此种方式用的较多。
-->
<bean id="user" class="com.spg.entity.User">
	<property name="name" value="test"/>
	<property name="age" value="21"/>
	<property name="birthday" ref="now"/>
</bean>
<bean id="now" class="java.util.Date"/>

1.6.4 使用 p 名称空间注入数据(本质还是调用 set 方法)

此种方式是通过在 xml 中导入 p 名称空间,使用 p:propertyName 来注入数据,它的本质仍然是调用类中的set 方法实现注入功能。
Java类代码:

/**
* 使用 p 名称空间注入,本质还是调用类中的 set 方法
*/
public class User {
	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 toString() {
		System.out.println(name+","+age+","+birthday);
	}
}

配置文件代码:

<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="user" class="com.spg.entity.User" 
			p:name="test" p:age="21" p:birthday-ref="now"/>
	<bean id="now" class="java.util.Date"></bean>
</beans>

1.6.5 注入集合属性

顾名思义,就是给类中的集合成员传值,它用的也是set方法注入的方式,只不过变量的数据类型都是集合。
我们这里介绍注入数组ListSetMapProperties。具体代码如下:
Java文件代码:

public class Demo {

	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);
	}
}

配置文件代码:

<!-- 注入集合数据
	List 结构的: array、list、set
	Map 结构的:map、entry;props、prop
-->
<bean id="demo" class="com.spg.common.Demo">
	<!-- 在注入集合数据时,只要结构相同,标签可以互换 -->
	<!-- 给数组注入数据 -->
	<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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值