Spring_06 案例1:使用spring的IoC的实现账户的CRUD

本文详细介绍了如何使用Spring的IoC容器管理和控制账户的增删查改(CRUD)操作,包括实体类、持久层、业务层的实现及配置文件的设置,并对比了XML与注解配置的方法。

一、使用spring的IoC的实现账户的CRUD

1、需求和技术要求

(1)需求

实现账户的 CRUD 操作

(2)技术要求

使用 spring 的 IoC 实现对象的管理
使用 DBAssit 作为持久层解决方案
使用 c3p0 数据源

(3)编写数据库
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);

2、代码

(1)持久层

实体类

/**
 * 	账户的实体类
 * @author
 */
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 + "]";
	}
}

持久层接口

/**
 * 账户的持久层方法
 * @author 
 *
 */
public interface IAccountDao {
	/**
	 * 	查询所有
	 * @return
	 */
	List<Account> findAllAccount();
	
	Account findAccountById(Integer id);
	
	void saveAccount(Account account);
	
	void updateAccount(Account account);
	
	void deleteAccount(Integer id);
}

持久层实现类

public class AccountDao implements IAccountDao{
	
	private QueryRunner runner;//!-- 在构造方法中:配置数据源 -->
	public void setRunner(QueryRunner runner) {
		this.runner = runner;
	}

	public List<Account> findAllAccount() {
		try {
			return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public Account findAccountById(Integer id) {
		try {
			return runner.query("select * from account where id=?",new BeanHandler<Account>(Account.class),id);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	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 id) {
		try {
			runner.update("delete from account where id=?",id);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}

(2)业务层

业务层接口

public interface IAccountService {
	/**
	 * 	查询所有
	 * @return
	 */
	List<Account> findAllAccount();
	
	Account findAccountById(Integer id);
	
	void saveAccount(Account account);
	
	void updateAccount(Account account);
	
	void deleteAccount(Integer id);
}

业务层实现类

/**
 * 	账户的业务层实现类
 * @author
 *
 */
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 id) {
		return accountDao.findAccountById(id);
	}

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

	public void updateAccount(Account account) {
		accountDao.updateAccount(account);
	}

	public void deleteAccount(Integer id) {
		accountDao.deleteAccount(id);
	}

}
(3)配置文件

pom.xml

<dependencies>
  	<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
	<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>8.0.17</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
	<dependency>
	    <groupId>commons-dbutils</groupId>
	    <artifactId>commons-dbutils</artifactId>
	    <version>1.4</version>
	</dependency>
	<dependency>
		<groupId>c3p0</groupId>
		<artifactId>c3p0</artifactId>
		<version>0.9.1.2</version>
	</dependency>
	<dependency>
	    <groupId>junit</groupId>
	    <artifactId>junit</artifactId>
		<version>4.10</version>
		<scope>test</scope>
	</dependency>  
  </dependencies>

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">
        
        <!-- 配置service对象 -->
        <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        	<!-- set方法注入dao -->
        	<property name="accountDao" ref="accountDao"></property>
        </bean>
        <!-- 配合dao -->
        <bean id="accountDao" class="com.itheima.dao.impl.AccountDao">
        	<!-- set方法注入runner -->
        	<property name="runner" ref="runner"></property>
        </bean>
        <!-- 配置QueryRunner(DBUtils依赖) -->
        <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        	<!-- 此处我们只注入了数据源,表明每条语句独立事务-->
        	<!-- 注入数据源(构造方法注入)constructor-arg -->
        	<constructor-arg name="ds" ref="dataSource"></constructor-arg>
        </bean>
        <!-- 配置数据源 (c3p0依赖)-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        	<!-- 连接数据库的必备信息 -->
        	<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
        	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy?useSSL=false&amp;serverTimezone=UTC"></property>
        	<property name="user" value="root"></property>
        	<property name="password" value="root"></property>
        </bean>
</beans>
(4)测试类
/**
 * 	使用Junit单元测试配置:测试我们的配置是否正确
 */
public class AccountServiceTest {
	@Test
	public void testfindAll() {
		//1、获取容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2、得到业务层对象
		IAccountService as = (IAccountService) ac.getBean("accountService",IAccountService.class);
		//3、执行方法
		List<Account> accounts = as.findAllAccount();
		for(Account account:accounts) {
			System.out.println(account);
		}
	}
	@Test
	public void testfindOne() {
		//1、获取容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		IAccountService as = (IAccountService) ac.getBean("accountService");
		Account account = as.findAccountById(2);
		System.out.println(account);
	}
	@Test
	public void testSaveAccount() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		IAccountService as = (IAccountService) ac.getBean("accountService");
		Account account = new Account();
		account.setName("ddd");
		account.setMoney(4000.0f);
		as.saveAccount(account);
	}
	@Test
	public void testUpdateAccount() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		IAccountService as = (IAccountService) ac.getBean("accountService");
		Account account = new Account();
		account.setId(4);
		account.setName("ddd");
		account.setMoney(1000.0f);
		as.updateAccount(account);
	}
	@Test
	public void testDeleteAccount() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		IAccountService as = (IAccountService) ac.getBean("accountService");
		as.deleteAccount(4);
		
	}
}

3、心得体会

分析测试了中的问题
	通过上面的测试类,我们可以看出,每个测试方法都重新获取了一次 spring 的核心容器,造成了不必要的重
	复代码,增加了我们开发的工作量。这种情况,在开发中应该避免发生。

有些同学可能想到了,我们把容器的获取定义到类中去。例如:
/**
* 测试类
* @author 黑马程序员
* @Company http://www.ithiema.com
* @Version 1.0
*/
public class AccountServiceTest {
	private ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
	private IAccountService as = ac.getBean("accountService",IAccountService.class);
}
这种方式虽然能解决问题,但是扔需要我们自己写代码来获取容器。
能不能测试时直接就编写测试方法,而不需要手动编码来获取容器呢?
请在今天的最后一章节找答案。

二、基于注解的 IOC 配置

1、写在前面

学习基于注解的 IoC 配置,大家脑海里首先得有一个认知,即注解配置和 xml 配置要实现的功能都是一样的,都是要降低程序间的耦合。只是配置的形式不一样。

关于实际的开发中到底使用xml还是注解,每家公司有着不同的使用习惯。所以这两种配置方式我们都需要掌握。

我们在讲解注解配置时,采用上一章节的案例,把 spring 的 xml 配置内容改为使用注解逐步实现。

2、代码

(1)持久层

实体类

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 + "]";
	}
	
	
}

持久层接口

/**
 * 账户的持久层方法
 * @author
 *
 */
public interface IAccountDao {
	
	List<Account> findAllAccount();
	
	Account findAccountById(Integer id);
	
	void saveAccount(Account account);
	
	void updateAccount(Account account);
	
	void deleteAccount(Integer id);
}

持久层实现类

@Repository("accountDao")
public class AccountDao implements IAccountDao{
	@Autowired//自动按照类型注入
	private QueryRunner runner;
	public void setRunner(QueryRunner runner) {
		this.runner = runner;
	}
	public List<Account> findAllAccount() {
		try {
			return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public Account findAccountById(Integer id) {
		try {
			return runner.query("select * from account where id=?",new BeanHandler<Account>(Account.class),id);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	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 id) {
		try {
			runner.update("delete from account where id=?",id);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}
(2)业务层

业务层接口

public interface IAccountService {
	/**
	 * 	查询所有
	 * @return
	 */
	List<Account> findAllAccount();
	
	Account findAccountById(Integer id);
	
	void saveAccount(Account account);
	
	void updateAccount(Account account);
	
	void deleteAccount(Integer id);
}

业务层实现类

/**
 * 	账户的业务层实现类
 * @author
 *
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService{
	@Autowired//自动按照类型注入
	private IAccountDao accountDao;
	 public void setAccountDao(IAccountDao accountDao) {
		this.accountDao = accountDao;
	}
	public List<Account> findAllAccount() {
		return accountDao.findAllAccount();
	}

	public Account findAccountById(Integer id) {
		return accountDao.findAccountById(id);
	}

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

	public void updateAccount(Account account) {
		accountDao.updateAccount(account);
	}

	public void deleteAccount(Integer id) {
		accountDao.deleteAccount(id);
	}

}
(3)配置文件

pom.xml

 <dependencies>
  	<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
	<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>8.0.17</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
	<dependency>
	    <groupId>commons-dbutils</groupId>
	    <artifactId>commons-dbutils</artifactId>
	    <version>1.4</version>
	</dependency>
	<dependency>
		<groupId>c3p0</groupId>
		<artifactId>c3p0</artifactId>
		<version>0.9.1.2</version>
	</dependency>
	<dependency>
	    <groupId>junit</groupId>
	    <artifactId>junit</artifactId>
		<version>4.10</version>
		<scope>test</scope>
	</dependency>  
  </dependencies>

bean.xml
注意: 基于注解整合时,导入约束时需要多导入一个 context 名称空间下的约束。

<?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"
    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">
 		
     	<!-- 告知spring创建容器时要扫描的包-->
        <context:component-scan base-package="com.itheima"></context:component-scan>
        <!-- 配置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.cj.jdbc.Driver"></property>
        	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy?useSSL=false&amp;serverTimezone=UTC"></property>
        	<property name="user" value="root"></property>
        	<property name="password" value="root"></property>
        </bean>
        
</beans>
(4)测试类
/**
 * 	使用Junit单元测试配置:测试我们的配置是否正确
 */
public class AccountServiceTest {
	@Test
	public void testfindAll() {
		//1、获取容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2、得到业务层对象
		IAccountService as = (IAccountService) ac.getBean("accountService",IAccountService.class);
		//3、执行方法
		List<Account> accounts = as.findAllAccount();
		for(Account account:accounts) {
			System.out.println(account);
		}
	}
	@Test
	public void testfindOne() {
		//1、获取容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		IAccountService as = (IAccountService) ac.getBean("accountService");
		Account account = as.findAccountById(2);
		System.out.println(account);
	}
	@Test
	public void testSaveAccount() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		IAccountService as = (IAccountService) ac.getBean("accountService");
		Account account = new Account();
		account.setName("ddd");
		account.setMoney(4000.0f);
		as.saveAccount(account);
	}
	@Test
	public void testUpdateAccount() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		IAccountService as = (IAccountService) ac.getBean("accountService");
		Account account = new Account();
		account.setId(4);
		account.setName("ddd");
		account.setMoney(1000.0f);
		as.updateAccount(account);
	}
	@Test
	public void testDeleteAccount() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		IAccountService as = (IAccountService) ac.getBean("accountService");
		as.deleteAccount(4);
		
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值