06-基于 XML 和注解 的 IOC 案例
目录
- 一、pom.xml 配置
- 二、创建接口、数据库表与实体类
- 1.数据库表
- 2.实体类
- 3.数据访问层
- Ⅰ 接口类
- Ⅱ 实现类
- 4.业务逻辑层
- Ⅰ 接口类
- Ⅱ 实现类
- 三、bean.xml
- 四、Test
- 五、基于注解
- 1. bean.xml
- 2. dao
- 3. service
新建一个 maven 工程
一、pom.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>spring05</groupId><artifactId>spring05</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><dependencies><!-- https://mvnrepository.com/artifact/org.springframework/spring-context --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.9.RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils --><dependency><groupId>commons-dbutils</groupId><artifactId>commons-dbutils</artifactId><version>1.7</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>6.0.6</version></dependency><!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.4</version></dependency><!-- https://mvnrepository.com/artifact/junit/junit --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies></project>
二、创建接口、数据库表与实体类
1.数据库表
create table account02(id int primary key auto_increment,name varchar(40),money float
);insert into account02(name,money) values ('aaa',10),('bbb',100),('ccc',1000);
2.实体类
创建 domain 文件夹
创建 Account 类生成get,set方法还有 tostring 方法
package com.domain;public class Account {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;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}
}
3.数据访问层
Ⅰ 接口类
package com.dao;import com.domain.Account;import java.util.List;/*** 描述:〈账户的持久层接口〉* @author zuiren* @create 2019/8/27* @since 1.0.0*/
public interface IAccountDao {/*** 查询所有* @return*/List<Account> findAllAccount();/*** 查询一个* @param accountId* @return*/Account findAccountById(Integer accountId);/*** 保存* @param account*/void saveAccount(Account account);/*** 更新* @param account*/void updateAccount(Account account);/*** 修改* @param accountId*/void deleteAccount(Integer accountId);
}
Ⅱ 实现类
package com.dao.Impl;import com.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;import java.sql.SQLException;
import java.util.List;/*** 描述:* 〈账户的持久层实现类〉** @author zuiren* @create 2019/8/27* @since 1.0.0*/
public class IAccountDaoImpl implements com.dao.IAccountDao {private QueryRunner runner;public IAccountDaoImpl(QueryRunner runner) {this.runner = runner;}public List<Account> findAllAccount() {try {return runner.query("select *from account02",new BeanListHandler<Account>(Account.class));}catch (Exception e){throw new RuntimeException(e);}}public Account findAccountById(Integer accountId) {try {return runner.query("select *from account02 where id = ?",new BeanHandler<Account>(Account.class),accountId);}catch (Exception e){throw new RuntimeException(e);}}public void saveAccount(Account account) {try {runner.update("insert into account02(name,money) values(?,?)",account.getName(),account.getMoney());}catch (SQLException e){e.printStackTrace();}}public void updateAccount(Account account) {try {runner.update("update account02 set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());}catch (SQLException e){e.printStackTrace();}}public void deleteAccount(Integer accountId) {try {runner.update("delete from account02 where id=?",accountId);}catch (SQLException e){e.printStackTrace();}}
}
4.业务逻辑层
Ⅰ 接口类
package com.service;import com.domain.Account;import java.util.List;/*** 描述:〈账户的业务层接口〉* @author zuiren* @create 2019/8/27* @since 1.0.0*/
public interface IAccountService {/*** 查询所有* @return*/List<Account> findAllAccount();/*** 查询一个* @param accountId* @return*/Account findAccountById(Integer accountId);/*** 保存* @param account*/void saveAccount(Account account);/*** 更新* @param account*/void updateAccount(Account account);/*** 修改* @param accountId*/void deleteAccount(Integer accountId);
}
Ⅱ 实现类
package com.service.Impl;import com.dao.IAccountDao;
import com.domain.Account;
import com.service.IAccountService;import java.util.List;/*** 描述:* 〈账户的业务层实现类〉** @author zuiren* @create 2019/8/27* @since 1.0.0*/
public class AccountServiceImpl implements IAccountService {private IAccountDao accountDao;public AccountServiceImpl(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 accountId) {accountDao.deleteAccount(accountId);}
}
三、bean.xml
在 resources 文件夹下创建 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/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><!--配置 Service--><bean id="accountService" class="com.service.Impl.AccountServiceImpl"><constructor-arg ref="accountDao"/><!--注入 dao--></bean><!--配置 Dao--><bean id="accountDao" class="com.dao.Impl.IAccountDaoImpl"><!--注入QueryRunner--><constructor-arg ref="runner"/></bean><!--配置QueryRunner 默认为单例对象--><bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"><!--QueryRunner 可以带参创建,也可以无参构造,有区别,你希望每条语句独立一个事务,还是所有的语句在同一个事务中由于此处是单表,一条语句的 crud 的操作,所以此时可以选择传入数据源--><!--注入数据源--><constructor-arg name="ds" ref="dataSource"/></bean><!--配置数据源--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><!--连接数据库的必备信息--><property name="driverClass" value="com.mysql.cj.jdbc.Driver"/><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=GMT"/><property name="user" value="root"/><property name="password" value="root"/></bean>
</beans>
四、Test
在 test 下创建 AccountServiceTest 类
package com.test;import com.domain.Account;
import com.service.IAccountService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.List;/*** 描述:* 〈使用 junit 单元测试:测试我们配置〉** @author zuiren* @create 2019/8/28* @since 1.0.0*/
public class AccountServiceTest {//1.获取容器ApplicationContext ac=null;//2.得到业务层对象IAccountService as=null;@Beforepublic void init(){//1.获取容器ac=new ClassPathXmlApplicationContext("bean.xml");//2.得到业务层对象as=ac.getBean("accountService",IAccountService.class);}@Testpublic void testFindAllAccount(){//3.执行方法List<Account> accounts = as.findAllAccount();for (Account account:accounts){System.out.println(account);}}@Testpublic void testFindAccountById(){//3.执行方法Account account=as.findAccountById(1);System.out.println(account);}@Testpublic void testSaveAccount(){//3.执行方法Account account=new Account();account.setName("卡兹克");account.setMoney(300);as.saveAccount(account);}@Testpublic void testUpdateAccount(){}@Testpublic void testDeleteAccount(){}
}
[TOC]
五、基于注解
1. 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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd"><!--告知 spring 在创建容器时要扫描的白--><context:component-scan base-package="com"/><bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"><!--注入数据源--><constructor-arg name="ds" ref="dataSource"/></bean><!--配置数据源--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><!--连接数据库的必备信息--><property name="driverClass" value="com.mysql.cj.jdbc.Driver"/><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=GMT"/><property name="user" value="root"/><property name="password" value="root"/></bean></beans>
2. dao
package com.dao.Impl;import com.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;import java.sql.SQLException;
import java.util.List;/*** 描述:* 〈账户的持久层实现类〉** @author zuiren* @create 2019/8/27* @since 1.0.0*/
@Repository(value = "accountDao")
public class IAccountDaoImpl implements com.dao.IAccountDao {@Autowiredprivate QueryRunner runner;public List<Account> findAllAccount() {try {return runner.query("select *from account02",new BeanListHandler<Account>(Account.class));}catch (Exception e){throw new RuntimeException(e);}}public Account findAccountById(Integer accountId) {try {return runner.query("select *from account02 where id = ?",new BeanHandler<Account>(Account.class),accountId);}catch (Exception e){throw new RuntimeException(e);}}public void saveAccount(Account account) {try {runner.update("insert into account02(name,money) values(?,?)",account.getName(),account.getMoney());}catch (SQLException e){e.printStackTrace();}}public void updateAccount(Account account) {try {runner.update("update account02 set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());}catch (SQLException e){e.printStackTrace();}}public void deleteAccount(Integer accountId) {try {runner.update("delete from account02 where id=?",accountId);}catch (SQLException e){e.printStackTrace();}}
}
3. service
package com.service.Impl;import com.dao.IAccountDao;
import com.domain.Account;
import com.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.List;/*** 描述:* 〈账户的业务层实现类〉** @author zuiren* @create 2019/8/27* @since 1.0.0*/
@Service(value = "accountService")
public class AccountServiceImpl implements IAccountService {@Autowiredprivate IAccountDao 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 accountId) {accountDao.deleteAccount(accountId);}
}
转载于:https://www.cnblogs.com/zuiren/p/11429727.html
06-基于 XML 和注解 的 IOC 案例相关推荐
- java学习day40(Spring)spring中的aop和基于XML以及注解的AOP配置
第1章 AOP 的相关概念[理解] 1.1AOP 概述 1.1.1 什么是 AOP AOP :全称是 Aspect Oriented Programming 即:面向切面编程. 简单的说它就是把我们程 ...
- 基于XML和注解的Spring Bean管理
文章目录 Spring工厂接口 BeanFactory接口 ApplicationContext 接口 Spring的bean管理的两种方式: 3 种实例化bean的方式(xml) 通过构造方法创建b ...
- 【Spring】基于注解的IOC案例
代码结构: bean.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=&quo ...
- 基于注解的IOC案例
pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...
- 基于XML及注解配置方式实现AOP及aspectJ表达式
aspectJ表达式结构 切入点表达式 execution (* com.sample.service.impl...(..)) 1.execution(): 表达式主体. 2.第一个号:表示返回类型 ...
- spring基于注解的IOC以及IoC的案例——概念
1.spring中ioc的常用注解 2.案例使用xml方式和注解方式实现单表的CRUD操作 持久层技术选择:dbutils 3.改造基于注解的ioc案例,使用纯注解的方式实现 spri ...
- java day58【 案例:使用 spring 的 IoC 的实现账户的 CRUD 、 基于注解的 IOC 配置 、 Spring 整合 Junit[掌握] 】...
第1章 案例:使用 spring 的 IoC 的实现账户的 CRUD 1.1 需求和技术要求 1.1.1 需求 1.1.2 技术要求 1.2 环境搭建 1.2.1 拷贝 jar 包 1.2.2 创建数 ...
- Spring基于XMLMysql | 注解Mysql的简单IOC案例
基于XML连接MySQL package com.it.domain;import java.io.Serializable;/*** @Author: 东方老赢* @Date: 2020/4/2 1 ...
- [JAVAEE]实验06:基于XML和基于注解的声明式事务管理方式模拟银行转账程序
一.实验目的: 熟练掌握声明式事务管理. 二.实验内容: 编写一个模拟银行转账的程序,要求在转账时通过Spring对事务进行控制. 三.实验要求: 分别使用基于XML和基于注解的声明式事务管理方式来实 ...
最新文章
- C/C++中“#”和“##”的作用和用法
- LeetCode-剑指 Offer 13. 机器人的运动范围
- ubuntu如何安装linux驱动程序,Ubuntu下如何安装驱动程序和应用软件?
- 五、Go语言复合数据类型(下)
- 最简单的设置按钮的鼠标悬停效果
- mysql 中文乱码 或 问号
- 1650显卡学计算机,适合老电脑升级?GTX1650显卡开箱,性价比依然不高!
- 奖池90万!阿里天池发起肺部CT多病种智能诊断大赛
- 实战系列-Spring Boot跨域解决方案
- Spring学习总结(27)——Spring常用注解再总结
- pythontime模块介绍_Python相关模块介绍
- 用汇编语言实现itoa函数
- 读写分离 mysql_详解MySQL实现主从复制过程及mycat读写分离步骤
- arcgis的numpy模块_01. Numpy模块
- js弹出框、遮罩层、可拖动学习
- 【Scratch考级99图】图12-等级考试scratch绘制 正八边形
- matlab spline三次样条插值x,Spline(三次样条插值)
- 第十三届蓝桥杯大赛软件类国赛 C/C++ 大学B组 试题 G: 故障
- 区块链测试网服务发布
- 软件需求工程 高校教学平台 培训计划