spring案例
本文目录
一.使用 spring 的 IoC 的实现账户的CRUD的例子
比如:我想实现对账户的CRUD的操作;运行程序,表现层调用业务层,业务层调用持久层,持久层中会完成对账户CRUD业务的操作。
一般情况下,他们之间的关系是:表现层依赖于业务层,业务层依赖于持久层,持久层依赖于实体类
所以程序需要在Client
中new一个AccountService实例
,AccountService
业务层中new一个AccountDao实例
,AccountDao
持久层中new一个Account实例
。在每一个类中由程序员自己new出来每一个类需要的对象,耦合度很高。
可以使用Spring最核心的思想——IOC(控制反转)容器 实现对象的管理
依赖注入主要有两种实现方式,分别是属性 setter 注入和构造方法注入。具体介绍如下。
- 属性 setter 注入
指 IoC 容器使用 setter 方法注入被依赖的实例。 - 构造方法注入
指 IoC 容器使用构造方法注入被依赖的实例。
1.需求
实现账户的 CRUD 操作。
- 使用 spring 的 IoC 实现对象的管理
- 使用 dbutils框架作为持久层解决方案
- 使用 c3p0 数据源
2.代码
程序结构
2.1 数据库准备
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
mysql数据库
2.2 新建Maven工程,导入Maven坐标
<dependencies>
<!--Spring的基础5个包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
导入成功:
2.3 编写实体类
/**
* 账户的实体类
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float 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 Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
2.4 编写持久层代码
/**
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* 保存账户
* @param account
*/
void saveAccount(Account account);
/**
* 更新
* @param account
*/
void updateAccount(Account account);
/**
* 删除
* @param accountId
*/
void deleteAccount(Integer accountId);
/**
* 根据id查询
* @param accountId
*/
Account findAccountById(Integer accountId);
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
}
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements IAccountDao {
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public void saveAccount(Account account) {
try {
runner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer accountId) {
try{
runner.update("delete from account where id=?",accountId);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer accountId) {
try {
return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public List<Account> findAllAccount() {
try {
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
2.5 编写业务层代码
/**
* 账户的业务层接口
*/
public interface IAccountService {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存
* @param account
*/
void saveAccount(Account account);
/**
* 更新
* @param account
*/
void updateAccount(Account account);
/**
* 删除
* @param acccountId
*/
void deleteAccount(Integer acccountId);
}
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService{
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void deleteAccount(Integer acccountId) {
accountDao.deleteAccount(acccountId);
}
}
2.6 编写配置文件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来加载实例
当项目工程启动时 bean.xml会被spring的ioc容器扫描所有的配置信息
然后根据配置的beanId,查找对应的class,然后为这个class生产实例,等待使用。
1.以前使用主动依赖的方式的方式在维护程序类之间的关系,耦合度太高,不利于程序扩展
2.现在使用IOC控制翻转的设计思想,将class的实例在工程启动时就生产实例,在业务中需要时
通过直接获取有效的降低了耦合,通过根据不同的业务进行组装搭配,实现另一个松散的耦合关系
-->
<!-- 配置domain -->
<bean id="account" class="com.dong.domain.Account"></bean>
<!-- 配置Service -->
<bean id="accountService" class="com.dong.service.Impl.AccountServiceImpl">
<!-- 注入dao -->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置Dao对象 -->
<bean id="accountDao" class="com.dong.Dao.Impl.AccountDaoImpl">
<!-- 注入QueryRunner -->
<property name="runner" ref="runner"></property>
</bean>
<!-- 配置QueryRunner -->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!-- 注入数据源 -->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 连接数据库的必备信息 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/user?useSSL=false"></property>
<property name="user" value="root"></property>
<property name="password" value="201703457"></property>
</bean>
</beans>
2.7 编写测试类
/**
* 测试类
* 调用业务层
*/
public class AccountServiceTest {
/**
* 测试查询所有
*/
@Test
public void testFindAll(){
//1.获取spring核心容器,加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取对象
AccountServiceImpl as = (AccountServiceImpl)ac.getBean("accountService");
//3.执行方法
List<Account> allAccount = as.findAllAccount();
for (Account account : allAccount) {
System.out.println(account);
}
}
/**
* 测试查询一个
*/
@Test
public void testFindOne(){
//1.获取spring核心容器,加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取对象
AccountServiceImpl as = (AccountServiceImpl)ac.getBean("accountService");
//3.执行方法
Account account = as.findAccountById(1);
System.out.println(account);
}
/**
* 测试保存
*/
@Test
public void testSave(){
//1.获取spring核心容器,加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取对象
Account account = (Account)ac.getBean("account");
account.setName("测试员");
account.setMoney(5000f);
AccountServiceImpl as = (AccountServiceImpl)ac.getBean("accountService");
//3.执行方法
as.saveAccount(account);
}
/**
* 测试更新
*/
@Test
public void testUpdate(){
//1.获取spring核心容器,加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取对象
AccountServiceImpl as = (AccountServiceImpl)ac.getBean("accountService");
//3.执行方法
Account account = as.findAccountById(1);
account.setMoney(10000f);
as.updateAccount(account);
}
/**
* 测试删除
*/
@Test
public void testDelete(){
//1.获取spring核心容器,加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取对象
AccountServiceImpl as = (AccountServiceImpl)ac.getBean("accountService");
//3.执行方法
as.deleteAccount(4);
}
}
3.运行程序
这里仅演示查询所有账户的运行结果:
通过上面的测试类,我们可以看出,每个测试方法都重新获取了一次 spring 的核心容器,造成了不必要的重复代码,增加了我们开发的工作量。这种情况,在开发中应该避免发生。
可能会想到把容器的获取定义到类中去,这种方式虽然能解决问题,但是仍需要我们自己写代码来获取容器。
能不能测试时直接就编写测试方法,而不需要手动编码来获取容器呢?其实是可以的,涉及到基于注解的 IOC 配置和spring整合Junit,感兴趣的小伙伴可以尝试下。
4.小结
通过Spring的IOC容器和依赖注入,在不需要自己去实例化的情况下,完成了实例化和控制。
推荐阅读
- Spring学习(1)-了解spring的各个模块.
- Spring学习(2)-程序间耦合和工厂模式解耦.
- Spring学习(3)-spring核心思想IOC(控制反转)和DI(依赖注入).
- Spring学习(4)-spring IOC中bean标签,常用属性,注入方法.
- Spring学习(5)-spring Bean的作用范围和生命周期.
- Spring学习(6)-spring简单例子.
欢迎点赞评论,指出不足,笔者由衷感谢o!