进阶之路:高级Spring整合技术解析

news2024/10/5 18:54:18

Spring整合

    • 1.1 Spring整合Mybatis思路分析
      • 1.1.1 环境准备
        • 步骤1:准备数据库表
        • 步骤2:创建项目导入jar包
        • 步骤3:根据表创建模型类
        • 步骤4:创建Dao接口
        • 步骤5:创建Service接口和实现类
        • 步骤6:添加jdbc.properties文件
        • 步骤7:添加Mybatis核心配置文件
        • 步骤8:编写应用程序
        • 步骤9:运行程序
      • 1.1.2 整合思路分析
    • 1.2 Spring整合Mybatis
      • 步骤1:项目中导入整合需要的jar包
      • 步骤2:创建Spring的主配置类
      • 步骤3:创建数据源的配置类
      • 步骤4:主配置类中读properties并引入数据源配置类
      • 步骤5:创建Mybatis配置类并配置SqlSessionFactory
      • 步骤6:主配置类中引入Mybatis配置类
      • 步骤7:编写运行类
      • 步骤8:运行程序
    • 1.3 Spring整合Junit
      • 1.3.1 环境准备
      • 1.3.2 整合Junit步骤
        • 步骤1:引入依赖
        • 步骤2:编写测试类
      • 知识点1:@RunWith
      • 知识点2:@ContextConfiguration

1.1 Spring整合Mybatis思路分析

1.1.1 环境准备

步骤1:准备数据库表

Mybatis是来操作数据库表,所以先创建一个数据库及表

create database spring_db character set utf8;
use spring_db;
create table tbl_account(
    id int primary key auto_increment,
    name varchar(35),
    money double
);
步骤2:创建项目导入jar包

项目的pom.xml添加相关依赖

<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>5.1.47</version>
    </dependency>
</dependencies>
步骤3:根据表创建模型类
public class Account implements Serializable {

    private Integer id;
    private String name;
    private Double money;
	//setter...getter...toString...方法略    
}
步骤4:创建Dao接口
public interface AccountDao {

    @Insert("insert into tbl_account(name,money)values(#{name},#{money})")
    void save(Account account);

    @Delete("delete from tbl_account where id = #{id} ")
    void delete(Integer id);

    @Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")
    void update(Account account);

    @Select("select * from tbl_account")
    List<Account> findAll();

    @Select("select * from tbl_account where id = #{id} ")
    Account findById(Integer id);
}
步骤5:创建Service接口和实现类
public interface AccountService {

    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List<Account> findAll();

    Account findById(Integer id);

}

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

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

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

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

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

    public List<Account> findAll() {
        return accountDao.findAll();
    }
}
步骤6:添加jdbc.properties文件

resources目录下添加,用于配置数据库连接四要素

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=root

useSSL:关闭MySQL的SSL连接

步骤7:添加Mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--读取外部properties配置文件-->
    <properties resource="jdbc.properties"></properties>
    <!--别名扫描的包路径-->
    <typeAliases>
        <package name="com.itheima.domain"/>
    </typeAliases>
    <!--数据源-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>
    <!--映射文件扫描包路径-->
    <mappers>
        <package name="com.itheima.dao"></package>
    </mappers>
</configuration>
步骤8:编写应用程序
public class App {
    public static void main(String[] args) throws IOException {
        // 1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml.bak");
        // 3. 创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        // 4. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 5. 执行SqlSession对象执行查询,获取结果User
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);

        Account ac = accountDao.findById(1);
        System.out.println(ac);

        // 6. 释放资源
        sqlSession.close();
    }
}
步骤9:运行程序

1.1.2 整合思路分析

Mybatis的基础环境我们已经准备好了,接下来就得分析下在上述的内容中,哪些对象可以交给Spring来管理?

  • Mybatis程序核心对象分析
    在这里插入图片描述

    从图中可以获取到,真正需要交给Spring管理的是SqlSessionFactory

  • 整合Mybatis,就是将Mybatis用到的内容交给Spring管理,分析下配置文件

    说明:

    • 第一行读取外部properties配置文件,Spring有提供具体的解决方案@PropertySource,需要交给Spring
    • 第二行起别名包扫描,为SqlSessionFactory服务的,需要交给Spring
    • 第三行主要用于做连接池,Spring之前我们已经整合了Druid连接池,这块也需要交给Spring
    • 前面三行一起都是为了创建SqlSession对象用的,那么用Spring管理SqlSession对象吗?回忆下SqlSession是由SqlSessionFactory创建出来的,所以只需要将SqlSessionFactory交给Spring管理即可。
    • 第四行是Mapper接口和映射文件[如果使用注解就没有该映射文件],这个是在获取到SqlSession以后执行具体操作的时候用,所以它和SqlSessionFactory创建的时机都不在同一个时间,可能需要单独管理。

1.2 Spring整合Mybatis

前面我们已经分析了Spring与Mybatis的整合,大体需要做两件事,

第一件事是:Spring要管理MyBatis中的SqlSessionFactory

第二件事是:Spring要管理Mapper接口的扫描

具体该如何实现,具体的步骤为:

步骤1:项目中导入整合需要的jar包

<dependency>
    <!--Spring操作数据库需要该jar包-->
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.10.RELEASE</version>
</dependency>
<dependency>
    <!--
		Spring与Mybatis整合的jar包
		这个jar包mybatis在前面,是Mybatis提供的
	-->
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
</dependency>

步骤2:创建Spring的主配置类

//配置类注解
@Configuration
//包扫描,主要扫描的是项目中的AccountServiceImpl类
@ComponentScan("com.itheima")
public class SpringConfig {
}

步骤3:创建数据源的配置类

在配置类中完成数据源的创建

public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}

步骤4:主配置类中读properties并引入数据源配置类

@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import(JdbcConfig.class)
public class SpringConfig {
}

步骤5:创建Mybatis配置类并配置SqlSessionFactory

public class MybatisConfig {
    //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        //设置模型类的别名扫描
        ssfb.setTypeAliasesPackage("com.itheima.domain");
        //设置数据源
        ssfb.setDataSource(dataSource);
        return ssfb;
    }
    //定义bean,返回MapperScannerConfigurer对象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.itheima.dao");
        return msc;
    }
}

说明:

  • 使用SqlSessionFactoryBean封装SqlSessionFactory需要的环境信息
    在这里插入图片描述

    • SqlSessionFactoryBean是前面我们讲解FactoryBean的一个子类,在该类中将SqlSessionFactory的创建进行了封装,简化对象的创建,我们只需要将其需要的内容设置即可。
    • 方法中有一个参数为dataSource,当前Spring容器中已经创建了Druid数据源,类型刚好是DataSource类型,此时在初始化SqlSessionFactoryBean这个对象的时候,发现需要使用DataSource对象,而容器中刚好有这么一个对象,就自动加载了DruidDataSource对象。
  • 使用MapperScannerConfigurer加载Dao接口,创建代理对象保存到IOC容器中
    在这里插入图片描述

    • 这个MapperScannerConfigurer对象也是MyBatis提供的专用于整合的jar包中的类,用来处理原始配置文件中的mappers相关配置,加载数据层的Mapper接口类
    • MapperScannerConfigurer有一个核心属性basePackage,就是用来设置所扫描的包路径

步骤6:主配置类中引入Mybatis配置类

@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}

步骤7:编写运行类

在运行类中,从IOC容器中获取Service对象,调用方法获取结果

public class App2 {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

        AccountService accountService = ctx.getBean(AccountService.class);

        Account ac = accountService.findById(1);
        System.out.println(ac);
    }
}

步骤8:运行程序

在这里插入图片描述

支持Spring与Mybatis的整合就已经完成了,其中主要用到的两个类分别是:

  • SqlSessionFactoryBean
  • MapperScannerConfigurer

1.3 Spring整合Junit

整合Junit与整合Druid和MyBatis差异比较大,为什么呢?Junit是一个搞单元测试用的工具,它不是我们程序的主体,也不会参加最终程序的运行,从作用上来说就和之前的东西不一样,它不是做功能的,看做是一个辅助工具就可以了。

1.3.1 环境准备

直接使用Spring与Mybatis整合的环境即可。

1.3.2 整合Junit步骤

在上述环境的基础上,我们来对Junit进行整合。

步骤1:引入依赖

pom.xml

<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>
步骤2:编写测试类

在test\java下创建一个AccountServiceTest,这个名字任意

//设置类运行器
@RunWith(SpringJUnit4ClassRunner.class)
//设置Spring环境对应的配置类
@ContextConfiguration(classes = {SpringConfiguration.class}) //加载配置类
//@ContextConfiguration(locations={"classpath:applicationContext.xml"})//加载配置文件
public class AccountServiceTest {
    //支持自动装配注入bean
    @Autowired
    private AccountService accountService;
    @Test
    public void testFindById(){
        System.out.println(accountService.findById(1));

    }
    @Test
    public void testFindAll(){
        System.out.println(accountService.findAll());
    }
}

注意:

  • 单元测试,如果测试的是注解配置类,则使用@ContextConfiguration(classes = 配置类.class)
  • 单元测试,如果测试的是配置文件,则使用@ContextConfiguration(locations={配置文件名,...})
  • Junit运行后是基于Spring环境运行的,所以Spring提供了一个专用的类运行器,这个务必要设置,这个类运行器就在Spring的测试专用包中提供的,导入的坐标就是这个东西SpringJUnit4ClassRunner
  • 上面两个配置都是固定格式,当需要测试哪个bean时,使用自动装配加载对应的对象,下面的工作就和以前做Junit单元测试完全一样了

知识点1:@RunWith

名称@RunWith
类型测试类注解
位置测试类定义上方
作用设置JUnit运行器
属性value(默认):运行所使用的运行期

知识点2:@ContextConfiguration

名称@ContextConfiguration
类型测试类注解
位置测试类定义上方
作用设置JUnit加载的Spring核心配置
属性classes:核心配置类,可以使用数组的格式设定加载多个配置类
locations:配置文件,可以使用数组的格式设定加载多个配置文件名称

后记
👉👉💕💕美好的一天,到此结束,下次继续努力!欲知后续,请看下回分解,写作不易,感谢大家的支持!! 🌹🌹🌹

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

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

相关文章

【案例】图片预览

效果图 如何让图片放大&#xff0c;大多数的UI组件都带有这种功能&#xff0c;今天给大家介绍的这个插件除了放大之外&#xff0c;还可以旋转、移动、翻转、旋转、二次放大&#xff08;全屏&#xff09; 实现 npm i v-viewer -Smain.js 中引入 import viewerjs/dist/viewer.c…

Go后端开发 -- 环境搭建

Go后端开发 – 环境搭建 文章目录 Go后端开发 -- 环境搭建一、环境配置二、IDE的选择三、使用go mod构建项目1.初始化项目2.添加依赖项3.运行项目 四、环境报错1.VS Code中gopls报错 一、环境配置 Go官网下载地址&#xff1a;https://golang.org/dl/ https://go.dev/dl/ Go官方…

javascript读取RFID卡号源码

本示例使用的读卡器&#xff1a;https://item.taobao.com/item.htm?spma1z10.5-c-s.w4002-21818769070.35.74185b43tGWQH5&id562957272162 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-…

【pentaho】kettle读取Hive表不支持bigint和timstamp类型解决。

一、bigint类型 报错: Unable to get value BigNumber(16) from database resultset显示kettle认为此应该是decimal类型(kettle中是TYPE_BIGNUMBER或称BigNumber)&#xff0c;但实际hive数据库中是big类型。 修改kettle源码解决&#xff1a; kettle中java.sql.Types到kettle…

记录SpringBoot包找不到主清单属性问题

之前从来没在意过这个问题&#xff0c;无数次项目打包都没有问题&#xff0c;突然有一天新建了个springboot项目打包部署的时候报错&#xff1a;no main manifest attribute, in xxxx-0.0.1-SNAPSHOT.jar 本明白什么原因&#xff0c;貌似也知道怎么去解决&#xff0c;以为是小…

vue3 在vite.config中无法使用import.meta.env.*的解决办法

第一种,优先使用第一种方法,其中参数mode就是自定义--mode的值,如果没写,就是production或development import { loadEnv } from vite export default ({ mode }) > {return defineConfig({plugins: [vue()],base:loadEnv(mode, process.cwd()).VITE_APP_NAME}) } 第二种 …

【Eachrts】水滴图

引入依赖 npm安装echarts、echarts-liquidfill插件 "echarts": "^5.4.2", "echarts-liquidfill": "^3.1.0",引入插件 import * as echarts from echarts; import echarts-liquidfill;示例 <template><div class"Liqu…

JSON Web Token JWT几种简单的绕过方法

JWT结构 JSON Web Token&#xff08;JWT&#xff09;是一个非常轻巧的规范。 这个规范允许我们使用JWT在用户和服务器之间传递安全可靠的信息。 JWT常被用于前后端分离&#xff0c;可以和Restful API配合使用&#xff0c;常用于构建身份认证机制 如图为JWT加密后的示例&…

工厂设备部如何选择合适的泵类设备状态监测技术

在现代工业生产中&#xff0c;泵类设备是工厂设备部不可或缺的一部分。为了确保泵类设备的高效运行和可靠性&#xff0c;预防故障和提高维护效率&#xff0c;工厂设备部需要选择合适的泵类设备状态监测技术。本文将探讨一些关键因素&#xff0c;帮助工厂设备部进行正确的选择。…

Ubuntu 常用命令之 awk 命令用法介绍

&#x1f4d1;Linux/Ubuntu 常用命令归类整理 AWK是一种处理文本文件的语言&#xff0c;是一个强大的文本分析工具。在Ubuntu系统下&#xff0c;AWK命令主要用于数据处理和生成报告。 AWK命令的参数主要有 -F&#xff1a;指定输入文件分隔符&#xff0c;FS变量就是指定输入字…

RHCE8 资料整理(目录)

RHCE8 资料整理&#xff08;目录&#xff09; 第一篇 基本配置第二篇 用户及权限管理第三篇 网络相关配置第四篇 存储管理第五篇 系统管理第 六 篇 软件管理第 七 篇 安全管理第 八 篇 容器管理第 九 篇 自动化管理工具ansible的使用 第一篇 基本配置 入口 第1章 安装RHEL8 第…

php伪协议 [SWPUCTF 2021 新生赛]PseudoProtocols

根据题目提示 我们直接用伪协议读取hint.php即可 php://filter/readconvert.base64-encode/resourcehint.php 我们把得到的编码拿去base64解密一下得到 那我们直接去访问一下 也可以用伪协议继续读取&#xff0c;只不过最后要base64解密一下 php://filter/readconvert.base6…

UE5 runtime模式下自定义视口大小和位置并跟随分辨率自适应缩放

本文旨在解决因UI问题导致屏幕中心位置不对的问题 处理前的现象&#xff1a;如果四周UI透明度都为1&#xff0c;那么方块的位置就不太对&#xff0c;没在中心 处理后的现象&#xff1a; 解决办法&#xff1a;自定义大小和视口偏移 创建一个基于子系统的类或者蓝图函数库(什么类…

期货高低板(期货价格飘升,市场掀起高低潮流)

什么是期货高低板&#xff1f; 期货是由交易所统一交易的标准化合约&#xff0c;商品的价格是通过供求关系来决定的。高低板则是期货交易中的常见现象&#xff0c;它表示了在交易过程中&#xff0c;价格波动超过了可设定的最高或最低价&#xff0c;于是交易系统便会出现高板或…

【为什么不能用浮点数表示金额?】

为什么不能用浮点数表示金额&#xff1f; ✅为什么不能用浮点数表示金额&#xff1f;✅拓展知识仓✅十进制转二进制✅不是所有数都能用二进制表示✅IEEE 754✅避免精度丢失 ✅为什么不能用浮点数表示金额&#xff1f; 主要原因&#xff1a; 因为不是所有小数都能用二进制表示&…

WPF实战项目二十一(客户端):设置默认首页

1、在Common文件夹里面新增接口IConfigureService&#xff0c;来专门配置启动过程设置的一些参数 public interface IConfigureService{void Configure();} 2、MainViewModel中继承接口IConfigureService&#xff0c;并实现 public class MainViewModel : BindableBase, ICon…

dell服务器 R740xd安装windows server 2019过程记录

公司有两台dell服务器型号是R740xd&#xff0c;增加了存储&#xff0c;更新系统到windows server 2019标准版。 查找了网上的系统安装方式&#xff0c;都没有实践成功&#xff0c;做一下工作记录&#xff0c;给大家做参考。 网络搜索到的两种方式&#xff0c;进行安装 &#x…

互操作性(Interoperability)如何影响着机器学习的发展?

互操作性&#xff08;Interoperability&#xff09;&#xff0c;也称为互用性&#xff0c;即两个系统之间有效沟通的能力&#xff0c;是机器学习未来发展中的关键因素。对于银行业、医疗和其他生活服务行业&#xff0c;我们期望那些用于信息交换的平台可以在我们需要时无缝沟通…

Halcon算子或函数fun(a :b : c1,c2 : d)中参数的双引号:和逗号,是什么意思

在创建新函数窗口可以看到算子一般有四个类型参数&#xff0c;每个类型参数用":"隔开&#xff0c;所以对每个算子打开F1帮助窗口会发现函数简介的括号里面都有3个":。 可以对照&#xff1a;new_fun ( input_img : output_img : input_control : out_control ) …

MACD 指标是什么?如何用它找出最佳买、卖点?

XM平台官网开户注册流程图解 FXCM福汇个人注册登录流程讲解Exness手机登录平台学习指南 MACD 指标 (Moving Average Convergence & Divergence) 中文名为平滑异同移动平均线指针&#xff0c;MACD 是在 1970 年代由美国人 Gerald Appel 所提出&#xff0c;是一项历史悠久且…