Understand how mybatis is initialized in the spring container

A fabricated belief 2020-11-09 12:49:34
understand mybatis initialized spring container


MyBatis The initialization process is Generate some necessary objects and put them in Spring In the container . The question is what objects are generated by this process ? When you meet MyBatis When initialization fails , How to find the right point to analyze the problem ? This article will introduce these problems .

This article is based on MyBatis 3 and Spring, Suppose the reader already knows how to use Maven and MyBatis, And understand Spring The container mechanism of .

One 、Mybatis Three piece set

We know MyBatis The main function of is by SqlSessionFactory and Mapper Both provide , initialization MyBatis It is to initialize these two kinds of objects . besides DataSource As a database access object is also essential . So first of all, we should remember MyBatis Initialization of the core set of three :

  • DataSource: It is a necessary data source object to access the database , If this initialization fails, the database cannot be accessed directly .
  • SqlSessionFactoryBean: This is Spring In the container SqlSessionFactory Encapsulation of the initialization process .
  • MapperScannerConfigurer: This is Spring In the container Mapper Encapsulation of the initialization process .

say concretely , A simple initialization process is as follows :

@Configuration
public class SpringMyBatisApplication {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(SpringMyBatisApplication.class);
}
@Bean
public DataSource dataSource() {
return ...;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
return ...;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
return ...;
}
}

Next, how to initialize each of the three sets , The following content can be operated in practice , Try it .

1. DataSource initialization

First we create an empty Maven project , stay pom.xml Add the following dependencies to :

<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!-- database -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.199</version>
</dependency>

This article focuses on demonstrating MyBatis The initialization process , So there's no complicated SQL, The database is an embedded database h2.

And then we were in com.hyd.mybatis3test Create a SpringMyBatisApplication class , The code was given earlier .

Corresponding DataSource The initialization implementation is as follows :

@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:test");
return dataSource;
}

2. SqlSessionFactoryBean initialization

SqlSessionFactoryBean It's right SqlSessionFactory Encapsulation of the initialization process ,Spring Meeting At the right time Execute this initialization process , To get the final SqlSessionFactory object .

SqlSessionFactoryBean The creation process of is as follows ( Note that the method signature changes from the previous one ):

@Bean
public SqlSessionFactoryBean sqlSessionFactory(
DataSource dataSource,
ResourcePatternResolver resolver
) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(resolver.getResources("classpath*:mappers/*.xml"));
return bean;
}

among :

  • The first parameter dataSource This is the data source object generated earlier ;
  • The second parameter resolver yes Spring Provided automatically , It is used to search all the xml file . This article will not include xml file , So this configuration is invalid , This line can be left blank , But it doesn't affect the program running .

3. MapperScannerConfigurer initialization

MapperScannerConfigurer Is to search all the... In the specified path Mapper Interface class ( Refer to it postProcessBeanDefinitionRegistry() Method ), And pass MapperFactoryBean Register it to MapperRegistry in .

@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer configurer = new MapperScannerConfigurer();
configurer.setBasePackage("com.hyd.mybatis3test");
return configurer;
}

4. Verify that the initialization process was successful

In order to verify that the above initialization process is completed , We are com.hyd.mybatis3test Create a Mapper class :

@Mapper
public interface SampleMapper {
@Update("create table if not exists user(id int)")
void createUserTable();
}

And one. Service class :

@Service
public static class SampleService {
@Autowired
private SampleMapper sampleMapper;
@PostConstruct
public void init() {
sampleMapper.createUserTable();
}
}

And don't forget to be in SpringMyBatisApplication Add a... To the top @ComponentScan("com.hyd.mybatis3test") annotation , otherwise Spring Will find SampleService.

function SpringMyBatisApplication.main() Method , We can find this in the output :

...
SampleMapper.createUserTable - ==> Preparing: create table if not exists user(id int)
SampleMapper.createUserTable - ==> Parameters:
SampleMapper.createUserTable - <== Updates: 0
...

This shows that the table created by SQL Statement executed successfully .

On the basis of the front three piece set ,MyBatis It also provides more encapsulation . With the foreshadowing of this article , I believe that readers will understand these packaging methods more easily .

Two 、@MapperScan annotation

@MapperScan Annotations are just MapperScannerConfigurer It's just the starter , Use this annotation , It can replace the previous one MapperScannerConfigurer initialization .

3、 ... and 、SpringBoot Automatic initialization

MyBatis Provide mybatis-spring-boot-starter Libraries are used in Spring Boot Automatic initialization in the project :

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>

This so-called automatic initialization is actually initialization SqlSessionFactory object . The initialization process consists of org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration complete , The required configuration is from "mybatis-" In the configuration property of prefix , For details, please refer to org.mybatis.spring.boot.autoconfigure.MybatisProperties class .

summary

All in all ,MyBatis The core process of initialization is the initialization of the three piece set . And in the Spring Boot Application , Combine automatic initialization with @MapperScan annotation , We don't need to manually initialize the three piece set , You can get... Directly from the container Mapper object .

版权声明
本文为[A fabricated belief]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云