【Spring篇】Spring整合

【Spring篇】Spring整合

🍓系列专栏:spring系列专栏

🍉个人主页:个人主页

目录

一、Spring整合

1.环境准备

2.整合思路分析

2.Spring整合Mybatis

3.Spring整合Junit

1.环境准备

2.整合Junit步骤 

二、图书推荐

1.《元宇宙Ⅱ:图解元技术区块链、元资产与Web3.0、元人与理想国(全三册)》

 2.《从零开始读懂量子力学(精装加强版)》


一、Spring整合

1.Spring整合Mybatis思路分析

1.环境准备

在准备环境的过程中,我们也来回顾下Mybatis开发的相关内容:

步骤 1: 准备数据库表
Mybatis 是来操作数据库表,所以先创建一个数据库及表
create database spring_db character set utf8;
use spring_db;
create table tbl_a***ount(
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>***.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 A***ount implements Serializable {
private Integer id;
private String name;
private Double money;
//setter...getter...toString...方法略
}
步骤 4: 创建 Dao 接口
public interface A***ountDao {

    @Insert("insert into tbl_a***ount(name,money)values(#{name},#{money})")
    void save(A***ount a***ount);

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

    @Update("update tbl_a***ount set name = #{name} , money = #{money} where id = #{id} ")
    void update(A***ount a***ount);

    @Select("select * from tbl_a***ount")
    List<A***ount> findAll();

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

    void save(A***ount a***ount);

    void delete(Integer id);

    void update(A***ount a***ount);

    List<A***ount> findAll();

    A***ount findById(Integer id);

}
@Service
public class A***ountServiceImpl implements A***ountService {

    @Autowired
    private A***ountDao a***ountDao;

    public void save(A***ount a***ount) {
        a***ountDao.save(a***ount);
    }

    public void update(A***ount a***ount){
        a***ountDao.update(a***ount);
    }

    public void delete(Integer id) {
        a***ountDao.delete(id);
    }

    public A***ount findById(Integer id) {
        return a***ountDao.findById(id);
    }

    public List<A***ount> findAll() {
        return a***ountDao.findAll();
    }
}
步骤 6: 添加 jdbc.properties 文件
resources 目录下添加,用于配置数据库连接四要素
jdbc.driver=***.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="***.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="***.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");
        // 3. 创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        // 4. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 5. 执行SqlSession对象执行查询,获取结果User
        A***ountDao a***ountDao = sqlSession.getMapper(A***ountDao.class);

        A***ount ac = a***ountDao.findById(1);
        System.out.println(ac);

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

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创建的时机都不在同一个时间,可能需要单独管理。

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
//包扫描,主要扫描的是项目中的A***ountServiceImpl类
@***ponentScan("***.itheima")
public class SpringConfig {
}
步骤 3: 创建数据源的配置类
在配置类中完成数据源的创建
public class Jdb***onfig {
@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
@***ponentScan("***.itheima")
@PropertySource("classpath:jdbc.properties")
@Import(Jdb***onfig.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("***.itheima.domain");
//设置数据源
ssfb.setDataSource(dataSource);
return ssfb;
}
//定义bean,返回MapperScannerConfigurer对象
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("***.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
@***ponentScan("***.itheima")
@PropertySource("classpath:jdbc.properties")
@Import({Jdb***onfig.class,MybatisConfig.class})
public class SpringConfig {
}
步骤 7: 编写运行类
在运行类中,从 IOC 容器中获取 Service 对象,调用方法获取结果
public class App2 {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

        A***ountService a***ountService = ctx.getBean(A***ountService.class);

        A***ount ac = a***ountService.findById(1);
        System.out.println(ac);
    }
}

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

3.Spring整合Junit

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

1.环境准备

这块环境,大家可以直接使用 Spring Mybatis 整合的环境即可。当然也可以重新创建一个,因为内容是一模一样,所以我们直接来看下项目结构即可:

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 下创建一个 A***ountServiceTest, 这个名字任意
//设置类运行器
@RunWith(SpringJUnit4ClassRunner.class)
//设置Spring环境对应的配置类
@ContextConfiguration(classes = SpringConfig.class)
public class A***ountServiceTest {
    //支持自动装配注入bean
    @Autowired
    private A***ountService a***ountService;

    @Test
    public void testFindById(){
        System.out.println(a***ountService.findById(1));

    }

    @Test
    public void testFindAll(){
        System.out.println(a***ountService.findAll());
    }


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

 知识点2@ContextConfiguration

笔记来自:黑马程序员SSM框架教程

二、图书推荐

1.《元宇宙Ⅱ:图解元技术区块链、元资产与Web3.0、元人与理想国(全三册)

看半小时漫画,通元宇宙未来100年,300幅手绘插图轻松读懂虚实共生的未来世界。剖析元宇宙三大定律、大统一方程、熵增定律、Web3.0、万亿元资产、元人与区块链文明,构建元宇宙大楼。讲透元技术区块链、元宇宙基石Web3.0到穿越未来的技术大革命。厘清8大产业规律和11大投资方向,从元宇宙经济学到财富自由2.0,构建NO.1无限∞世界的数字空间,从元人到理想国。

 内容简介

这是一个全新的时代:Web3.0构建的经济体系,DID身份的跨平台操作,数字NFT的原子级镜像,以及DeFi的无摩擦元资产再分配......2022年,奇点出现:元人即将诞生;元资产即将分配;元宇宙正在成形。本套书通过元宇宙三大定律、大统一方程、熵增定律、Web3.0、万亿元资产、元人与区块链文明构建了元宇宙第一大楼。第1-80层:数字人展位、电子宠物、数字藏品、3D沉侵式旅游、DeFi。第81-160层:AI、VR、AR、MR、DAO、Web3.0、边缘计算。第161-214+层:多场景阅读、4K空间、跨链许可、维度转换、无限∞世界。

 

迫不及待的小伙伴也可以访问下面的链接了解详情:

《元宇宙Ⅱ:图解元技术区块链、元资产与Web3.0、元人与理想国(全三册)》

 2.从零开始读懂量子力学(精装加强版)

量子力学全新升级版,每章增加了背景知识和相关的理论实验介绍, 新增了现代量子科技的前沿话题。增加21幅手绘物理插画和作者本人创作的科技诗词。从微小的原子到浩瀚的宇宙,从每一滴水到闪亮的钻石,从划破夜空的激光到你身边的手机,所有事物的背后都有量子力学在主宰!让我们从零开始,一起走进量子力学的世界!

 

 量子力学是现代物理学的基石,推动了科学技术的快速发展。在今天,量子依然是新闻热点。

本书将为广大科技爱好者系统、严谨地介绍量子力学的基本原理和应用。读者需要熟悉高中物理和数学的相关内容,愿意学习科学的思维方式。虽然量子力学是一门有着神秘面纱、打破生活常识、颠覆人类认知的现代科学,但是读者只要愿意随着本书一起思考,就一定能够清楚地了解量子力学理论的基本概念,最终全面认识它在科学体系中的作用和对现代技术的贡献。

本书的叙述方式是一边讲解科学理论,一边介绍重要的实验现象和科学原理的应用。本书在第一篇中依次讲解了状态叠加、波粒二象性、不确定性原理等基本概念;在第二篇中介绍了量子力学在凝聚态物理和基本粒子物理领域中的应用。同时,对由量子力学催生的现代电子技术,也着重做了介绍。

 迫不及待的小伙伴也可以访问下面的链接了解详情:

《从零开始读懂量子力学(精装加强版) 解密诺贝尔奖聚焦话题量子纠缠的奥秘 零基础学量子力学》

🍓本次送 3 本书 ,评论区抽3位小伙伴送书🍓

书籍名称:《元宇宙Ⅱ:图解元技术区块链、元资产与Web3.0、元人与理想国(全三册)》

活动时间:截止到 2023-05-08 20:00:00

抽奖方式:利用程序进行抽奖。

参与方式:关注博主、点赞、收藏,评论区评论 "夏日炎炎,码不停息!"

🍓 获奖名单🍓

在下小吉.

勾栏听曲_0

几分醉意.

名单公布时间: 2023-05-08 20:00:00

转载请说明出处内容投诉
CSS教程_站长资源网 » 【Spring篇】Spring整合

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买