20201124黄春跃
20201124黄春跃
知识点
使用 spring 的 IoC 的实现账户的CRUD
需求
实现账户的 CRUD 操作
技术要求
使用 spring 的 IoC 实现对象的管理
使用 DBUtils 作为持久层解决方案
使用 c3p0 数据源
环境搭建
导入 jar 包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2.1</version>
</dependency>
<!-- 数据库工具类 -->
<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
创建数据库和编写实体类
DROP TABLE IF EXISTS `tb_account`;
CREATE TABLE `tb_account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL
DEFAULT NULL,
`money` float(255, 0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE =
utf8_general_ci ROW_FORMAT = Dynamic;
insert into tb_account(name,money) values('aaa',1000);
insert into tb_account(name,money) values('bbb',1000);
insert into tb_account(name,money) values('ccc',1000);
@Data
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
}
编写持久层代码
public interface IAccountDao {
/**
* 保存
* @param account
*/
void save(Account account);
/**
* 更新
* @param account
*/
void update(Account account);
/**
* 删除
* @param accountId
*/
void delete(Integer accountId);
/**
* 根据 id 查询
* @param accountId
* @return
*/
Account findById(Integer accountId);
/**
* 查询所有
* @return
*/
List<Account> findAll();
}
public class AccountDaoImpl implements IAccountDao {
private QueryRunner runner;
public void setRunner(QueryRunner runner){
this.runner = runner;
}
@Override
public void save(Account account) {
try {
runner.update("insert into tb_account(name,money)values(?,?)",account.getName(),account.getMoney());
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
@Override
public void update(Account account) {
try {
runner.update("update tb_account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
@Override
public void delete(Integer accountId) {
try {
runner.update("delete from tb_account where id=?",accountId);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
@Override
public Account findById(Integer accountId) {
try {
return runner.query("select * from tb_account where id=?",new BeanHandler<Account>(Account.class),accountId);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
@Override
public List<Account> findAll() {
try {
return runner.query("select * from tb_account",new BeanListHandler<Account>(Account.class));
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
编写业务层代码
public interface IAccountService {
/**
* 保存账户
* @param account
*/
void saveAccount(Account account);
/**
* 更新账户
* @param account
*/
void updateAccount(Account account);
/**
* 删除账户
* @param accountId
*/
void deleteAccount(Integer accountId);
/**
* 根据 id 查询账户
* @param accountId
* @return
*/
Account findAccountById(Integer accountId);
/**
* 查询所有账户
* @return
*/
List<Account> findAllAccount();
}
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void saveAccount(Account account) {
accountDao.save(account);
}
@Override
public void updateAccount(Account account) {
accountDao.update(account);
}
@Override
public void deleteAccount(Integer accountId) {
accountDao.delete(accountId);
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findById(accountId);
}
@Override
public List<Account> findAllAccount() {
return accountDao.findAll();
}
}
创建并编写配置文件
<?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 id="service" class="com.itlaobing.spring.service.Impl.AccountServiceImpl">
<property name="accountDao" ref="dao" />
</bean>
<bean id="dao" class="com.itlaobing.spring.dao.Impl.AccountDaoImpl">
<property name="runner" ref="queryRunner" />
</bean>
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="datasource"/>
</bean>
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="user" value="root" />
<property name="password" value="" />
</bean>
</beans>
测试
public class IAccountServiceTest {
private ApplicationContext context;
private IAccountService service;
@Before
public void setUp() throws Exception {
context = new ClassPathXmlApplicationContext("Spring.xml");
service = context.getBean(IAccountService.class);
}
@Test
public void saveAccount() {
Account account = new Account();
account.setName("abc");
account.setMoney(1000.1f);
service.saveAccount(account);
}
@Test
public void updateAccount() {
Account account = service.findAccountById(1);
account.setMoney(9999999f);
account.setName("黄百万");
service.updateAccount(account);
}
@Test
public void deleteAccount() {
service.deleteAccount(5);
}
@Test
public void findAccountById() {
Account account = service.findAccountById(1);
System.out.println(account);
}
@Test
public void findAllAccount() {
List<Account> list = service.findAllAccount();
for(Account account : list) {
System.out.println(account);
}
}
}
基于注解的 IOC 配置
学习基于注解的 IoC 配置,大家脑海里首先得有一个认知,即注解配置和 xml 配置要实现的功能都是一
样的,都是要降低程序间的耦合。只是配置的形式不一样。
关于实际的开发中到底使用xml还是注解,每家公司有着不同的使用习惯。所以这两种配置方式我们都
需要掌握。
我们在讲解注解配置时,采用上一章节的案例,把 spring 的 xml 配置内容改为使用注解逐步实现
添加 jar 包
在基于注解的配置中,我们还要多一个 aop 的 jar 包
使用@Component 注解配置管理的资源
创建 spring 的 xml 配置文件并开启对注解的支持
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://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.itlaobing" />
<!-- 配置 runner 此处我们只注入了数据源,scope="prototype"表明每条语句独立事务-
->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner"
scope="prototype">
<constructor-arg index="0" 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/userinfo"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
注意:
基于注解整合时,导入约束时需要多导入一个 context 名称空间下的约束
context:component-scan: 告知spring在初始化容器时扫描包
base-package:要扫描的包名,多个包之间使用逗号隔开
测试:
@Test
public void getBean(){
ApplicationContext ctx = new
ClassPathXmlApplicationContext("beans.xml");
IAccountService as = ctx.getBean("accountService",
IAccountService.class);
System.out.println(as);
}
近期评论