第一章:搭建整合环境
-
整合说明:
-
SSM 整合可以使用多种方式,此次会选择 XML + 注解的方式
-
-
整合的思路:
- 搭建整合环境
- 把 Spring 的配置搭建完成
- 再使用 Spring 整合 SpringMVC 框架
- 最后使用 Spring 整合 MyBatis 框架
-
创建数据库和表结构:
create database ssm; use ssm; create table account( id int primary key auto_increment, name varchar(20), money double );
-
创建 Maven Java Web 工程,并导入依赖:
- 部署 SSM_Web 的项目,只要把 SSM_Web 项目加入到 Tomcat 服务器中即可
public class TestSpring { @Test public void run(){ //创建工厂,加载配置文件 ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); //获取 service 对象调用方法 AccountService accountService = ac.getBean(AccountService.class); accountService.findAll(); } }
- 部署 SSM_Web 的项目,只要把 SSM_Web 项目加入到 Tomcat 服务器中即可
-
编写实体类,在 SSM_domain 项目中编写:
public class Account implements Serializable { private Integer id; private String name; private Double money; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
-
编写Service 接口:
public interface AccountService { public List<Account> findAll(); }
-
编写 Service 接口的实现类,在 Service 包中创建 Impl 包:
@Service public class AccountServiceImpl implements AccountService { @Override public List<Account> findAll() { System.out.println("业务层逻辑:查询所有账号"); return null; } }
第二章:Spring 框架代码的编写
-
搭建和测试 Spring 的开发环境:
- 在 SSM_Web 项目中创建 applicationContext.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" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 开启注解扫描,要扫描的是service --> <context:component-scan base-package="com.qcby.service"/> </beans>
- 在 SSM_Web 项目中编写测试方法,进行测试:
public class TestSpring { @Test public void run(){ //创建工厂,加载配置文件 ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); //获取 service 对象调用方法 AccountService accountService = ac.getBean(AccountService.class); accountService.findAll(); } }