[SSM]Spring6整合JUnit5与集成MyBatis3.5

目录

十七、Spring6整合JUnit5

17.1Spring对JUnit4的支持

17.2Spring对JUnit5的支持

十八、Spring6集成MyBatis3.5

18.1实现步骤

18.2具体实现

18.3spring配置文件的import


十七、Spring6整合JUnit5

17.1Spring对JUnit4的支持

  • 准备工作:

<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.3</version></dependency><!--spring对junit4支持的依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><!--这个版本spring6,既支持JUnit4又支持JUnit5--><version>6.0.3</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency>
</dependencies>

声明Bean

package com.hhb.bean;
​
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
​
@Component
public class User {@Value("张三")private String name;
​public User(String name) {this.name = name;}
​public User() {}
​public String getName() {return name;}
​public void setName(String name) {this.name = name;}
​@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +'}';}
}

spring.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/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
​<context:component-scan base-package="com.hhb.bean"/>
</beans>

单元测试

package com.hhb.test;
​
import com.hhb.bean.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
​
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class SpringJUnit4Test {@Autowiredprivate User user;
​@Testpublic void testUser() {System.out.println(user.getName());}
​@Testpublic void testUser1() {System.out.println(user.getName());}
​@Testpublic void testUser2() {System.out.println(user.getName());}
}

 

  • Spring提供的方便主要是这几个注解:

    • @RunWith(SpringJUnit4ClassRunner.class)

    • @ContextConfiguration("classpath:spring.xml")

  • 在单元测试类上使用这两个注解之后,在单元测试类中的属性上可以使用@Autowired,比较方便。

17.2Spring对JUnit5的支持

  • 引入JUnit5的依赖

<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.3</version></dependency><!--spring对junit4支持的依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><!--这个版本spring6,既支持JUnit4又支持JUnit5--><version>6.0.3</version></dependency>
​<!--junit5依赖--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>5.9.0</version><scope>test</scope></dependency>
</dependencies>

单元测试

package com.hhb.test;
​
import com.hhb.bean.User;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
​
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:spring.xml")
public class SpringJUnit5Test {
​@Autowiredprivate User user;
​@Testpublic void testUser(){System.out.println(user.getName());}
​@Testpublic void testUser2(){System.out.println(user.getName());}
}
  • 在JUnit5当中,可以使用Spring提供的以下两个注解,标注到单元测试类上,这样类当中就可以使用@Autowired注解了。

    • ExtendWith(SpringExtension.class)

    • ContextConfiguration("classpath:spring.xml")

十八、Spring6集成MyBatis3.5

18.1实现步骤

  • 第一步:准备数据库表

    • 使用t_act表(账户表)

  • 第二步:引入依赖

    • spring-context

    • spring-jdbc

    • mysql驱动

    • mybatis

    • mybatis-spring:mybatis提供的与spring框架集成的依赖

    • 德鲁伊连接池

    • junit

  • 第三步:基于三层架构实现,提前准备好所有的包

    • com.hhb.bank.mapper

    • com.hhb.bank.service

    • com.hhb.bank.service.impl

    • com.hhb.bank.pojo

  • 第四步:编写pojo

    • Account,属性私有化,提供公开的setter、getter和toString。

  • 第五步:编写mapper接口

    • AccountMapper接口,定义方法

  • 第六步:编写mapper配置文件

    • 在配置文件中配置命名空间,以及每一个方法对应的sql。

  • 第七步:编写service接口和service接口实现类

    • AccountService

    • AccountServiceImpl

  • 第八步:编写jdbc.properties配置文件

    • 数据库连接池相关信息

  • 第九步:编写mybatis-config.xml配置文件

    • 该文件可以没有,大部分的配置可以转移到spring配置文件中。

    • 如果遇到mybatis相关的系统级配置,还是需要这个文件。

  • 第十步:编写spring.xml配置文件

    • 组件扫描

    • 引入外部的属性文件

    • 数据源

    • SqlSessionFactoryBean配置

      • 注入mybatis核心配置文件路径

      • 指定别名包

      • 注入数据源

    • Mapper扫描配置器

      • 指定扫描的包

    • 事务管理器DataSourceTransactionManager

      • 注入数据源

    • 启用事务注解

      • 注入事务管理器

  • 第十一步:编写测试程序,并添加事务,进行测试。

18.2具体实现

  • 第一步:准备数据库表

  • 第二步:引入依赖

<?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>org.example</groupId><artifactId>spring016-sm</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging>
​<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.3</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>6.0.3</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.10</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.1.0</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.13</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency></dependencies>
​<properties><maven.compiler.source>20</maven.compiler.source><maven.compiler.target>20</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
​
</project>

 

  • 第三步:基于三层架构实现,所以提前创建好所有的包

  • 第四步:编写pojo

 
package com.hhb.bank.pojo;
​
public class Account {private String actno;private Double balance;
​public Account() {}
​@Overridepublic String toString() {return "Account{" +"actno='" + actno + '\'' +", balance=" + balance +'}';}
​public Account(String actno, Double balance) {this.actno = actno;this.balance = balance;}
​public String getActno() {return actno;}
​public void setActno(String actno) {this.actno = actno;}
​public Double getBalance() {return balance;}
​public void setBalance(Double balance) {this.balance = balance;}
}

 

  • 第五步:编写mapper接口

package com.hhb.bank.mapper;
​
import com.hhb.bank.pojo.Account;
​
import java.util.List;
​
//这就是DAO
public interface AccountMapper {//该接口的实现类不需要写,是mybatis通过动态代理机制生成的实现类
​//新增账户int insert(Account account);
​//根据账号删除账户int deleteByActno(String actno);
​//修改账户int update(Account account);
​//根据账号查询账户Account selectByActno(String actno);
​//查询所有账户List<Account> selectAll();
}
  • 第六步:编写mapper配置文件,如果接⼝叫做AccountMapper,配置⽂件必须是AccountMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hhb.bank.mapper.AccountMapper">
​<insert id="insert">insert into t_actvalues (#{actno}, #{balance})</insert>
​<delete id="deleteByActno">deletefrom t_actwhere actno = #{actno}</delete>
​<update id="update">update t_actset balance = #{balance}where actno = #{actno}</update>
​<select id="selectByActno" resultType="Account">select *from t_actwhere actno = #{actno}</select>
​<select id="selectAll" resultType="Account">select *from t_act</select>
​
</mapper>
  • 第七步:编写service接口和service接口实现类,注意编写的service实现类纳入IoC容器管理

package com.hhb.bank.service;
​
import com.hhb.bank.pojo.Account;
​
import java.util.List;
​
public interface AccountService {//开户int save(Account act);
​//销户int deleteByActno(String actno);
​//修改账户int modify(Account act);
​//查询账户Account getByActno(String actno);
​//获取所有账户List<Account> getAll();
​//转账void transfer(String fromActno, String toActno, double money);
​
}
package com.hhb.bank.service.impl;
​
import com.hhb.bank.mapper.AccountMapper;
import com.hhb.bank.pojo.Account;
import com.hhb.bank.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
​
import java.util.List;
​
@Transactional
@Service("accountService")
public class AccountServiceImpl implements AccountService {
​@Autowiredprivate AccountMapper accountMapper;
​@Overridepublic int save(Account act) {return accountMapper.insert(act);}
​@Overridepublic int deleteByActno(String actno) {return accountMapper.deleteByActno(actno);}
​@Overridepublic int modify(Account account) {return accountMapper.update(account);}
​@Overridepublic Account getByActno(String actno) {return accountMapper.selectByActno(actno);}
​@Overridepublic List<Account> getAll() {return accountMapper.selectAll();}
​@Overridepublic void transfer(String fromActno, String toActno, double money) {Account fromAct = accountMapper.selectByActno(fromActno);if (fromAct.getBalance() < money) {throw new RuntimeException("余额不足");}Account toAct = accountMapper.selectByActno(toActno);fromAct.setBalance(fromAct.getBalance() - money);toAct.setBalance(toAct.getBalance() + money);int count = accountMapper.update(fromAct);/*String s = null;s.toString();*/
​count += accountMapper.update(toAct);if (count != 2) {throw new RuntimeException("转账失败");}}
}
  • 第八步:编写jdbc.properties配置文件,放在类的根路径下

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring6
jdbc.username=root
jdbc.password=030522
  • 第九步:编写mybatis-config.xml配置文件,放在类的根路径下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--帮助我们打印mybatis的日志信息。sql语句等。--><settings><setting name="logImpl" value="STDOUT_LOGGING"/></settings>
</configuration>
  • 第十步:编写spring.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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
​<!--组件扫描--><!--<context:component-scan base-package="com.hhb.bank"/>--><!--在spring的核心配置文件中引入子spring配置文件--><import resource="common.xml"/>
​<!--引入外部的属性配置文件--><context:property-placeholder location="jdbc.properties"/>
​<!--数据源--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean>
​<!--配置SqlSessionFactoryBean--><bean class="org.mybatis.spring.SqlSessionFactoryBean"><!--注入数据源--><property name="dataSource" ref="dataSource"/><!--指定mybatis核心配置文件--><property name="configLocation" value="mybatis-config.xml"/><!--指定别名--><property name="typeAliasesPackage" value="com.hhb.bank.pojo"/></bean>
​<!--Mapper扫描配置器,主要扫描Mapper接口,生成代理类--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.hhb.bank.mapper"/></bean>
​<!--事务管理器--><bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean>
​<!--启用事务注解--><tx:annotation-driven transaction-manager="txManager"/>
</beans>
  • 第十一步:编写测试程序,并添加事务,进行测试

package com.hhb.bank.test;
​
import com.hhb.bank.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
public class BankSMTest {@Testpublic void testSM(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");AccountService accountService = applicationContext.getBean("accountService", AccountService.class);try {accountService.transfer("act001", "act002", 10000);System.out.println("转账成功");} catch (Exception e){e.printStackTrace();}}
}

18.3spring配置文件的import

  • spring配置文件有多个,并且可以在spring的核心配置文件中使用import进行引入,我们可以将组件扫描单独定义到一个配置文件中,如下:

common.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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
​<!--组件扫描--><context:component-scan base-package="com.hhb.bank"/>
</beans>
  • 在核心配置文件中引入:

<import resource="common.xml"/>
  • 注意:在实际开发中,service单独配置到一个文件中,dao单独配置到一个文件中,然后在核心配置文件中引入,养成好习惯。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/16201.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

华为数通HCIA-网络参考模型(TCP/IP)

网络通信模式 作用&#xff1a;指导网络设备的通信&#xff1b; OSI七层模型&#xff1a; 7.应用层&#xff1a;由应用层协议&#xff08;http、FTP、Telnet.&#xff09;为应用程序产生对应的数据&#xff1b; 6.表示层&#xff1a;将应用层产生的数据转换成网络设备看得懂…

C语言文件io操作

一、fopen 在C语言中&#xff0c;操作文件之前应该先打开文件。使用<stdio.h>头文件中的fopen()函数可以打开文件&#xff0c;因为FILE也是结构体&#xff0c;我们通过返回一个文件指针就可以对文件进行操作。在用完fopen之后要记得关闭该文件流。 用法&#xff1a; F…

Linux 进程查找、杀死方案集合

一、查找进程 方式一 ps 命令&#xff1a;显示当前活动进程的快照。 # 显示所有用户的所有进程 $ ps aux# 显示所有进程的完整信息 $ ps -ef# 常用参数 -a&#xff1a;显示所有进程&#xff0c;包括其他用户的进程。 -u <用户>&#xff1a;仅显示指定用户的进程信息。 -x…

【多模态】20、OVR-CNN | 使用 caption 来实现开放词汇目标检测

文章目录 一、背景二、方法2.1 学习 视觉-语义 空间2.2 学习开放词汇目标检测 三、效果 论文&#xff1a;Open-Vocabulary Object Detection Using Captions 代码&#xff1a;https://github.com/alirezazareian/ovr-cnn 出处&#xff1a;CVPR2021 Oral 一、背景 目标检测数…

Redis系列一:介绍

介绍 The open source, in-memory data store used by millions of developers as a database, cache, streaming engine, and message broker. 相关资源 Redis 官网&#xff1a;https://redis.io/ 源码地址&#xff1a;https://github.com/redis/redis Redis 在线测试&#…

学习使用axios,绑定动态数据

目录 axios特性 案例一&#xff1a;通过axios获取笑话 案例二&#xff1a;调用城市天气api接口数据实现天气查询案例 axios特性 支持 Promise API 拦截请求和响应&#xff08;可以在请求前及响应前做某些操作&#xff0c;例如&#xff0c;在请求前想要在这个请求头中加一些…

msbuild - 对话

MSBuild是一个用于构建、部署和测试.NET应用程序的命令行工具。它是微软开发工具包&#xff08;Microsoft Build Tools&#xff09;中的一部分&#xff0c;常用于自动化构建和发布过程。 可以使用MSBuild来构建Visual Studio项目或解决方案&#xff0c;并根据需要执行各种操作…

springboot 整合tx-mybaits 实现crud操作

一 操作案例 1.1 工程结构 1.2 pom文件的配置 <!--spring boot的依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId…

华为数通HCIA-地址分类及子网划分

ip地址&#xff08;逻辑地址&#xff09; 作用&#xff1a;唯一标识一张网卡 特点&#xff1a;设备天生没有&#xff0c;需要人为配置&#xff0c;可以随时修改 格式&#xff1a;点分十进制 大小&#xff1a;32bit 组成&#xff1a;网络位主机位 网络位&#xff1a;用于标…

Java:使用spring中的工厂模式ServiceLocatorFactoryBean实现多方支付功能

目录 项目结构完整代码测试参考视频 本文实现功能&#xff1a;使用spring中的工厂模式&#xff1a;ServiceLocatorFactoryBean实现多方支付功能。 项目结构 $ tree . ├── pom.xml └── src└── main└── java└── com└── example└── demo├── Application…

【机器学习】Multiple Variable Linear Regression

Multiple Variable Linear Regression 1、问题描述1.1 包含样例的X矩阵1.2 参数向量 w, b 2、多变量的模型预测2.1 逐元素进行预测2.2 向量点积进行预测 3、多变量线性回归模型计算损失4、多变量线性回归模型梯度下降4.1 计算梯度4.2梯度下降 首先&#xff0c;导入所需的库 im…

Reinforcement Learning with Code 【Code 1. Tabular Q-learning】

Reinforcement Learning with Code 【Code 1. Tabular Q-learning】 This note records how the author begin to learn RL. Both theoretical understanding and code practice are presented. Many material are referenced such as ZhaoShiyu’s Mathematical Foundation o…

Windows 10 中无法最大化任务栏中的程序

方法1&#xff1a;仅选择选项 PC 屏幕 如果您使用双显示器&#xff0c;有时这可能会发生在您的 1 台计算机已插入但您正在访问的应用程序正在另一台计算机上运行的情况下&#xff0c;因此您看不到任何选项。因此&#xff0c;请设置仅在主计算机上显示显示的 PC 屏幕选项。 第…

搭建自己第一个golang程序

概念&#xff1a; golang 和 java有些类似&#xff0c;配置好环境就可以直接编写运行了&#xff1b;这里分两种&#xff1a; 一.shell模式 创建一个go类型的文件 往里面编写代码 二.开发工具模式 这里的开发工具 我选用goland package mainimport "fmt"func mai…

Ubuntu 20.04.4 LTS安装Terminator终端(Linux系统推荐)

Terminator终端可以在一个窗口中创建多个终端&#xff0c;并且可以水平、垂直分割&#xff0c;运行ROS时很方便。 sudo apt install terminator这样安装完成后&#xff0c;使用快捷键Ctrl Alt T打开的就是新安装的terminator终端&#xff0c;可以使用以下方法仍然打开ubuntu默…

【数据结构】实验四:循环链表

实验四 循环链表 一、实验目的与要求 1&#xff09;熟悉循环链表的类型定义和基本操作&#xff1b; 2&#xff09;灵活应用循环链表解决具体应用问题。 二、实验内容 题目一&#xff1a;有n个小孩围成一圈&#xff0c;给他们从1开始依次编号&#xff0c;从编号为1的小孩开…

异步检索在 Elasticsearch 中的理论与实践

异步检索在 Elasticsearch 中的理论与实践 https://www.elastic.co/guide/en/elasticsearch/reference/8.1/async-search.html#submit-async-search 引言 Elasticsearch 是一种强大的分布式搜索和分析引擎&#xff0c;它能够快速地存储、搜索和分析大量数据。在处理大规模数据时…

Prometheus中的关键设计

1、标准先行&#xff0c;注重生态 Prometheus 最重要的规范就是指标命名方式&#xff0c;数据格式简单易读。比如&#xff0c;对于应用层面的监控&#xff0c;可以要求必须具备这几个信息。 指标名称 metric Prometheus 内置建立的规范就是叫 metric&#xff08;即 __name__…

正则表达式 —— Awk

Awk awk&#xff1a;文本三剑客之一&#xff0c;是功能最强大的文本工具 awk也是按行来进行操作&#xff0c;对行操作完之后&#xff0c;可以根据指定命令来对行取列 awk的分隔符&#xff0c;默认分隔符是空格或tab键&#xff0c;多个空格会压缩成一个 awk的用法 awk的格式…

学习day53

今天主要是做一个案例 TodoList 组件化编码流程&#xff1a; 1. 拆分静态组件&#xff1a;组件要按照功能点拆分&#xff0c;命名不要与html元素冲突 2.实现动态组件&#xff1a;考虑好数据的存放位置&#xff0c;数据是一个组件在用&#xff0c;还是一些组件在用&#xff1a…