Spring整合Mybatis、junit纯注解
如何创建一个Spring项目


错误问题
不知道什么原因,大概是依赖版本不兼容、java版本不对的问题,折磨了好久就是搞不成。
主要原因看pom.xml配置
pom.xml配置
java版本
由于是跟着22年黑马视频做的,java版本换成了jdk-11,用21以上不行,其他没试过。
<properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
Project Structure设置


依赖
需要修改的下面几个

<?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>com.example</groupId><artifactId>SpringDemo</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.10.RELEASE</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.16</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.10.RELEASE</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.6</version></dependency><!-- 添加logback-classic依赖 --><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.3</version></dependency><!-- 添加logback-core依赖 --><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-core</artifactId><version>1.2.3</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.2.10.RELEASE</version></dependency></dependencies>
</project>
文件结构

下面只介绍用上的
数据库
create database mybatis;
use mybatis;
create table user
(id int auto_incrementprimary key,username varchar(20) null,password varchar(20) null,gender char null,addr varchar(30) null
);
application.properties
把mybatis换成自己数据库名即可
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false
jdbc.username=root
jdbc.password=root
MybatisConfig
package com.example.config;import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class MybatisConfig {@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setTypeAliasesPackage("com.example.domain");sqlSessionFactoryBean.setDataSource(dataSource);return sqlSessionFactoryBean;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer() {MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setBasePackage("com.example.dao");return mapperScannerConfigurer;}
}
JdbcConfig
package com.example.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;import javax.sql.DataSource;// 从 application.properties 文件中加载配置属性
@PropertySource("application.properties")
public class JdbcConfig {// 注入数据库驱动类名@Value("${jdbc.driver}")private String driver;// 注入数据库连接 URL@Value("${jdbc.url}")private String url;// 注入数据库用户名@Value("${jdbc.username}")private String username;// 注入数据库密码@Value("${jdbc.password}")private String password;/*** 创建并配置 Druid 数据源* @return 配置好的数据源对象*/@Beanpublic DataSource dataSource() {DruidDataSource ds = new DruidDataSource();// 设置数据库驱动类名,使用从配置文件中注入的值ds.setDriverClassName(driver);// 设置数据库连接 URL,使用从配置文件中注入的值ds.setUrl(url);// 设置数据库用户名,使用从配置文件中注入的值ds.setUsername(username);// 设置数据库密码,使用从配置文件中注入的值ds.setPassword(password);return ds;}
}
User
package com.example.domain;public class User {private int id;private String username;private String password;private String gender;private String addr;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getAddr() {return addr;}public void setAddr(String addr) {this.addr = addr;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +", gender='" + gender + '\'' +", addr='" + addr + '\'' +'}';}
}
UserDao
package com.example.dao;import com.example.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;import java.util.List;@Mapper
public interface UserDao {@Select("select * from mybatis.user")public List<User> selectAll();@Select("select * from mybatis.user where id = #{id}")public User selectById(Integer id);
}
UserService
package com.example.service;import com.example.domain.User;import java.util.List;public interface UserService {public List<User> selectAll();public User selectById(Integer id);
}
UserServiceImpl
package com.example.service.impl;import com.example.dao.UserDao;
import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service("userService")
public class UserServiceImpl implements UserService {//private BookDao bookDao = new BookDaoImpl();// 5.为了解决代码耦合度过高,使用IOC容器将创建对象的过程在容器中实现,不再使用new@Autowiredprivate UserDao userDao;@Overridepublic List<User> selectAll() {return userDao.selectAll();}@Overridepublic User selectById(Integer id){return userDao.selectById(id);}
}
logback.xml(无关紧要)
<?xml version="1.0" encoding="UTF-8"?>
<configuration><!-- console表示当前日志信息是可以输出到控制台的--><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>(%level %boldBlue(%d{HH:mm:ss.SSS}) %cyan(【%thread】) %boldGreen(%logger{15}) - %msg %n)</pattern></encoder></appender><root level="debug"><appender-ref ref="STDOUT" /></root>
</configuration>
AppTest(Spring整合mybatis的运行程序)
package com.example;import com.example.config.SpringConfig;
import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;import java.util.List;public class AppTest {public static void main(String[] args) {// 获取IOC容器AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);UserService userService = ctx.getBean(UserService.class);List<User> users = userService.selectAll();System.out.println(users);ctx.close();}
}
UserServiceTest(测试类)
package com.example.service;import com.example.config.SpringConfig;
import com.example.domain.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;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {@Autowiredprivate UserService userService;@Testpublic void selectAllTest() {List<User> users = userService.selectAll();System.out.println(users);}@Testpublic void selectByIdTest() {Integer id = 3;User user = userService.selectById(id);System.out.println(user);}
}
整合思路
整合mybaits
在mybatisConfig用SqlSessionFactoryBean封装SqlSessionFactory需要的环境信息
连接信息用jdbcConfig实现,dataSource对象是自动加载的

使用MapperScannerConfigurer加载Dao接口,创建代理对象保存到IOC容器中

主配置类SpringConfig中引入Mybatis配置类
- @Configuration:声明这是一个配置类
- @ComPonentScan:使得 Spring 容器能够自动扫描和发现被特定注解标注的类,并将它们注册为 Spring 容器中的 Bean
- @PropertySource:加载外部属性文件,将外部的属性文件(如
.properties、.yml等)中的属性加载到 Spring 的Environment中,为应用程序提供配置信息。 - @Import:这里是导入配置类,可以将其他的 Spring 配置类导入到当前配置类中,让 Spring 容器能够扫描和管理这些配置类中定义的 Bean。
@Configuration
@ComponentScan("com.examole")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}
整合Jnuit
//设置类运行器
@RunWith(SpringJUnit4ClassRunner.class)//设置Spring环境对应的配置类
@ContextConfiguration(classes = {SpringConfiguration.class}) //加载配置类
- 单元测试,如果测试的是注解配置类,则使用@ContextConfiguration(classes = 配置类.class)
- 单元测试,如果测试的是配置文件,则使用 名,...}) @ContextConfiguration(locations={配置文件名,...})
- Junit运行后是基于Spring环境运行的,所以Spring提供了一个专用的类运行器,这个务必要设 置,这个类运行器就在Spring的测试专用包中提供的,导入的坐标就是这个东西 SpringJUnit4ClassRunner
- 上面两个配置都是固定格式,当需要测试哪个bean时,使用自动装配加载对应的对象,下面的工 作就和以前做Junit单元测试完全一样了
注解解释
@RunWith

@ContextConfiguration

相关文章:
Spring整合Mybatis、junit纯注解
如何创建一个Spring项目 错误问题 不知道什么原因,大概是依赖版本不兼容、java版本不对的问题,折磨了好久就是搞不成。 主要原因看pom.xml配置 pom.xml配置 java版本 由于是跟着22年黑马视频做的,java版本换成了jdk-11,用21以…...
vue3中customRef的用法以及使用场景
1. 基本概念 customRef 是 Vue3 提供的用于创建自定义响应式引用的 API,允许显式地控制依赖追踪和触发响应。它返回一个带有 get 和 set 函数的工厂函数来自定义 ref 的行为。 1.1 基本语法 import { customRef } from vuefunction createCustomRef(value) {retu…...
深入探讨数据库索引类型:B-tree、Hash、GIN与GiST的对比与应用
title: 深入探讨数据库索引类型:B-tree、Hash、GIN与GiST的对比与应用 date: 2025/1/26 updated: 2025/1/26 author: cmdragon excerpt: 在现代数据库管理系统中,索引技术是提高查询性能的重要手段。当数据量不断增长时,如何快速、有效地访问这些数据成为了数据库设计的核…...
两数相加:链表操作的基础与扩展
两数相加:链表操作的基础与扩展 引言 链表(Linked List)是一种灵活且高效的数据结构,特别适用于动态增删操作。无论是初学者还是资深程序员,链表的基本操作都是算法学习中的重要一环。而 “两数相加” 问题则是链表操…...
智能码二维码的成本效益分析
以下是智能码二维码的成本效益分析: 成本方面 硬件成本 标签成本:二维码标签本身价格低廉,即使进行大规模应用,成本也相对较低。如在智能仓储中,塑料托盘加二维码方案的标签成本几乎可以忽略不计4。扫描设备成本&…...
分布式系统学习:小结
关于分布式系统的学习就暂时告一段落了,下面整理了个思维导图,只涉及分布式的一些相关概念,需要的可自取。后面准备写下关于AI编程相关的技术文章,毕竟要紧跟时代的脚步嘛 思维导图xmind文件下载地址:https://download…...
基于STM32的阿里云智能农业大棚
目录 前言: 项目效果演示: 一、简介 二、硬件需求准备 三、硬件框图 四、CubeMX配置 4.1、按键、蜂鸣器GPIO口配置 4.2、ADC输入配置 4.3、IIC——驱动OLED 4.4、DHT11温湿度读取 4.5、PWM配置——光照灯、水泵、风扇 4.6、串口——esp8266模…...
WGCLOUD使用介绍 - 如何监控ActiveMQ和RabbitMQ
根据WGCLOUD官网的信息,目前没有针对ActiveMQ和RabbitMQ这两个组件专门做适配 不过可以使用WGCLOUD已经具备的通用监测模块:进程监测、端口监测或者日志监测、接口监测 来对这两个组件进行监控...
Win11画图工具没了怎么重新安装
有些朋友想要简单地把图片另存为其他格式,或是进行一些编辑,但是发现自己的Win11系统里面没有画图工具,这可能是因为用户安装的是精简版的Win11系统,解决方法自然是重新安装一下画图工具,具体应该怎么做呢?…...
一次飞利浦电视机的意外童锁和卫星天线的重新授权(近30年前的电视)以及骂万能遥控
电视机被密码保护了,一开始我愣住了,意外是系统保护.防止修改.后来知道一个名,叫童锁.不知道的时候搜飞利浦电视密码,百度的结果 大多是0000,1234这个之类的, 试过都是不行的.偶然看到一个0711, 结果可以了, 再试试的时候,要求输入两次0711才解锁. 后来就在系统里改为0000,并且…...
“AI质量评估系统:智能守护,让品质无忧
嘿,各位小伙伴们!今天咱们来聊聊一个在现代社会中越来越重要的角色——AI质量评估系统。你知道吗?在这个快速发展的时代,产品质量已经成为企业生存和发展的关键。而AI质量评估系统,就像是我们的智能守护神,…...
Ubuntu 顶部状态栏 配置,gnu扩展程序
顶部状态栏 默认没有配置、隐藏的地方 安装使用Hide Top Bar 或Just Perfection等进行配置 1 安装 sudo apt install gnome-shell-extension-manager2 打开 安装的“扩展管理器” 3. 对顶部状态栏进行配置 使用Hide Top Bar 智能隐藏,或者使用Just Perfection 直…...
sqlite3 学习笔记
文章目录 前言SQL的概念与表格相关的操作i.创建表格(增)ii 删除表格(删)iii 更改表格(改)iv 查询表格(查) 与记录相关的操作i 插入记录ii 删除记录iii 查询记录iv 修改记录 Linux中使…...
cloc下载和使用
cloc(Count Lines of Code)是一个跨平台的命令行工具,用于计算代码行数。以下是下载和使用 cloc 的步骤: 下载 cloc 对于 Windows 用户: 访问 cloc 的 GitHub 仓库:https://github.com/AlDanial/cloc在 …...
自定义数据集使用框架的线性回归方法对其进行拟合
代码 import torch import numpy as np import torch.nn as nncriterion nn.MSELoss()data np.array([[-0.5, 7.7],[1.8, 98.5],[0.9, 57.8],[0.4, 39.2],[-1.4, -15.7],[-1.4, -37.3],[-1.8, -49.1],[1.5, 75.6],[0.4, 34.0],[0.8, 62.3]])x_data data[:, 0] y_data data…...
FPGA 使用 CLOCK_LOW_FANOUT 约束
使用 CLOCK_LOW_FANOUT 约束 您可以使用 CLOCK_LOW_FANOUT 约束在单个时钟区域中包含时钟缓存负载。在由全局时钟缓存直接驱动的时钟网段 上对 CLOCK_LOW_FANOUT 进行设置,而且全局时钟缓存扇出必须低于 2000 个负载。 注释: 当与其他时钟约束配合…...
RabbitMQ模块新增消息转换器
文章目录 1.目录结构2.代码1.pom.xml 排除logging2.RabbitMQConfig.java3.RabbitMQAutoConfiguration.java 1.目录结构 2.代码 1.pom.xml 排除logging <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/PO…...
SpringBoot 使用海康 SDK 和 flv.js 显示监控画面
由于工作需要将海康监控的画面在网页上显示,经过查找资料最终实现了。过程中发现网上的资料都不怎么完整,没办法直接用,所以记录一下,也帮后人避避坑。我把核心代码放到下面,完整工程放到码云上。完整工程带有前端页面…...
分析一个深度学习项目并设计算法和用PyTorch实现的方法和步骤
算法设计分析 明确问题类型 分类问题:例如图像分类,像判断一张图片是猫还是狗。算法设计可能会采用经典的卷积神经网络(CNN)结构,如ResNet、VGG等。以ResNet为例,其通过残差连接解决了深层网络训练时梯度…...
大模型训练策略与架构优化实践指南
标题:大模型训练策略与架构优化实践指南 文章信息摘要: 该分析全面探讨了大语言模型训练、架构选择、部署维护等关键环节的优化策略。在训练方面,强调了pre-training、mid-training和post-training的不同定位与目标;在架构选择上…...
机器学习:支持向量机
支持向量机(Support Vector Machine)是一种二类分类模型,其基本模型定义为特征空间上的间隔最大的广义线性分类器,其学习策略便是间隔最大化,最终可转化为一个凸二次规划问题的求解。 假设两类数据可以被 H x : w T x…...
Spring Boot(6)解决ruoyi框架连续快速发送post请求时,弹出“数据正在处理,请勿重复提交”提醒的问题
一、整个前言 在基于 Ruoyi 框架进行系统开发的过程中,我们常常会遇到各种有趣且具有挑战性的问题。今天,我们就来深入探讨一个在实际开发中较为常见的问题:当连续快速发送 Post 请求时,前端会弹出 “数据正在处理,请…...
「 机器人 」扑翼飞行器控制的当前挑战与后续潜在研究方向
前言 在扑翼飞行器设计与控制方面,虽然已经取得了显著的进步,但在飞行时间、环境适应性、能量利用效率及模型精度等方面依旧存在亟待解决的挑战。以下内容概括了这些挑战和可能的改进路径。 1. 当前挑战 1.1 飞行时间短 (1)主要原因 能源存储有限(电池容量小)、驱动系…...
2023年版本IDEA复制项目并修改端口号和运行内存
2023年版本IDEA复制项目并修改端口号和运行内存 1 在idea中打开server面板,在server面板中选择需要复制的项目右键,点击弹出来的”复制配置…(Edit Configuration…)“。如果idea上没有server面板或者有server面板但没有springbo…...
Spring Boot中如何实现异步处理
在 Spring Boot 中实现异步处理可以通过使用 Async 注解和 EnableAsync 注解来实现。以下是如何配置和使用异步处理的步骤和示例代码。 步骤: 启用异步支持: 在 Spring Boot 配置类上使用 EnableAsync 注解启用异步处理。使用 Async 注解异步方法&…...
微信小程序怎么制作自己的小程序?手把手带你入门(适合新手小白观看)
对于初学者来说,制作一款微信小程序总感觉高大上,又害怕学不会。不过,今天我就用最简单、最有耐心的方式,一步一步给大家讲清楚!让你知道微信小程序的制作,居然可以这么轻松(希望你别吓跑啊!)。文中还加了实战经验&…...
Vuex 的核心概念:State, Mutations, Actions, Getters
Vuex 的核心概念:State, Mutations, Actions, Getters Vuex 是 Vue.js 的官方状态管理库,提供了集中式的状态管理机制。它的核心概念包括 State(状态)、Mutations(变更)、Actions(动作…...
Python OrderedDict 实现 Least Recently used(LRU)缓存
OrderedDict 实现 Least Recently used(LRU)缓存 引言正文 引言 LRU 缓存是一种缓存替换策略,当缓存空间不足时,会移除最久未使用的数据以腾出空间存放新的数据。LRU 缓存的特点: 有限容量:缓存拥有固定的…...
3.3 Go函数可变参数
可变参数(variadic parameters)是一种允许函数接受任意数量参数的机制。它在函数定义中使用 ...type 来声明参数类型,所有传递的参数会被收集为一个切片,函数内部可以像操作普通切片一样处理这些参数。 package mainimport "…...
EventBus事件总线的使用以及优缺点
EventBus EventBus (事件总线)是一种组件通信方法,基于发布/订阅模式,能够实现业务代码解耦,提高开发效率 发布/订阅模式 发布/订阅模式是一种设计模式,当一个对象的状态发生变化时,所有依赖…...
