Spring入门之使用 spring 的 IOC 解决程序耦合(Spring环境搭建)(03-01)

2023-03-09,,

3.1 案例的前期准备

1.使用的案例是:账户的业务层和持久层的依赖关系解决(就是有两个账户实现转账之类的事情,后期继续用这个案例)
2.准备环境:在开始 spring 的配置之前,我们要先准备一下环境。(由于这里是使用 spring 解决依赖关系,并不是真正的要做增删改查操作,所以此时没必要写实体类。并且在此处使用的是 java 工程,不是 java web 工程。)

3.1.1 准备 spring 的开发包

官网:http://spring.io/
下载地址:http://repo.springsource.org/libs-release-local/org/springframework/spring
解压:(Spring 目录结构:)

docs :API 和开发规范.
libs :jar 包和源码.
schema :约束.
我们使用的版本是 spring5.0.2。
特别说明:
spring5 版本是用 jdk8 编写的,所以要求我们的 jdk 版本是 8 及以上。同时 tomcat 的版本要求 8.5 及以上。(maven项目)

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

/**
* 账户的业务层接口
*/
public interface IAccountService {
/**
* 保存账户(此处只是模拟,并不是真的要保存)
*/
void saveAccount();
}
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = new AccountDaoImpl();//此处的依赖关系有待解决
@Override
public void saveAccount() {
accountDao.saveAccount();
}
}

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

/**
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* 保存账户
*/
void saveAccount();
}
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements IAccountDao {
@Override
public void saveAccount() {
System.out.println("保存了账户");
}
}

3.2 基于 XML 的配置(入门案例)[掌握]

3.2.1 第一步:拷贝必备的 jar 包到工程的 lib 目录中

3.2.2 第二步:在类的根路径下创建一个任意名称的 xml 文件(不能是中文)

接着给配置文件导入约束:
/spring-framework-5.0.2.RELEASE/docs/spring-framework-reference/html5/core.html
(这个是xml配置文件开头约束网页,介意在浏览器添加书签收藏查的时候比较方便。进去网页后点击Core然后Ctrl+F搜索你要的相关约束。)

比如这个时候需要的:

<?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>

3.2.3 第三步:让 spring 管理资源,在配置文件中配置 service 和 dao

(1)配置文件里的三个标签:
bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中
id 属性:对象的唯一标识。
class 属性:指定要创建对象的全限定类名

<!-- 配置 service -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
</bean>
<!-- 配置 dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>

3.2.4 测试配置是否成功

(后期学MyBatis就用test注解来测试)

/**
* 模拟一个表现层
*/
public class Client {
/**
* 使用 main 方法获取容器测试执行
*/
public static void main(String[] args) {
//1.使用 ApplicationContext 接口,就是在获取 spring 容器
//后面会介绍ApplicationContext 接口
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 bean 的 id 获取对象
IAccountService aService = (IAccountService) ac.getBean("accountService");
System.out.println(aService);
IAccountDao aDao = (IAccountDao) ac.getBean("accountDao");
System.out.println(aDao);
}
}

运行结果·:成功

Spring入门之使用 spring 的 IOC 解决程序耦合(Spring环境搭建)(03-01)的相关教程结束。

《Spring入门之使用 spring 的 IOC 解决程序耦合(Spring环境搭建)(03-01).doc》

下载本文的Word格式文档,以方便收藏与打印。