Springboot-mybatis framework use and source code parsing

Source: Internet
Author: User

Preface:
现在微服务架构基本已经成为一种架构正确了,而SpringBoot技术也已经被应用在各个项目中。SpringBoot不仅仅那些传统的好处,更多是可以与其他组件进行结合,使用户可以更方便的使用。比如SpringBoot-Kafka、SpringBoot-Mybatis、SpringBoot-RabbitMQ等等。本文,分析一下SpringBoot-Mybatis的使用及其源码,让读者可以更深入的了解下SpringBoot是如何帮我们简化配置,节约开发时间的。

1.springboot-mybatis use

1) Add Maven dependency

<parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>1.5.3.RELEASE</version></parent>   <dependency>        <groupId>org.mybatis.spring.boot</groupId>        <artifactId>mybatis-spring-boot-starter</artifactId>        <version>1.1.1</version>    </dependency>    <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <version>5.1.32</version>    </dependency>**2)在application.yml中添加DataSource配置**

Spring
DataSource
Url:jdbc:mysql://localhost:3306/test
Username:root
Password:root
Driver-class-name:com.mysql.jdbc.driver

MyBatis
Mapper-locations:classpath:mapper/*.xml #注意: Be sure to correspond to the path where the mapper map XML file is located
Type-aliases-package:com.example.demo.mybatis # Note: The path of the corresponding entity class
3) Add SQL to Mapper/user.xml

<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en"
"Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace= "Com.example.demo.mybatis.IUser" >
<select id= "GetUser" parametertype= "int"
Resulttype= "Com.example.demo.mybatis.User" >
SELECT *
From USER
WHERE id = #{userid}
</select>
</mapper>
4) Add Iuser interface

Public interface Iuser {
Public User getUser (int id);
}
5) Add User entity class

@Data
public class User {
private int id;
private String name;
Private String Dept;
Private String phone;
Private String website;
}
6) Add the most important link in application (Note: @MapperScan corresponds to the iuser path)

@SpringBootApplicationbr/> @MapperScan ("Com.example.demo.mybatis")

public static void Main (string[] args) {
Springapplication springapplication = new Springapplication (springbootstudyapplication.class);
Springapplication.run (args);
}
}
7) Add test

@RunWith (Springrunner.class) br/> @SpringBootTest (Classes=springbootstudyapplication.class)
< p="">

@Autowiredprivate IUser userMapper;@Testpublic void contextLoads() {    User user = userMapper.getUser(3);    System.out.println(user);//User(id=3, name=jack, dept=devp, phone=xxx, website=www.baidu.com)}

}
Test success

2. Write before source analysis

SpringBoot一般以配置居多,各种类之间的关系错综复杂。我们在分析SpringBoot的分析中,一定要抓住核心点。比如当前Mybatis的分析,结合Spring-Mybatis来看,我们应该主动创建DataSource、SqlSessionFactoryBean、MapperFactoryBean,并且把这些bean添加到Spring容器中。但是从当前的使用配置来看,这些bean我们都没有显示声明,没有像Spring-Mybatis使用的时候那样显示声明在beans.xml中,所以一定是SpringBoot帮我们做了这些工作,我们的重点要放在SpringBoot如何帮我们声明这些bean。仔细回想一下,SpringBoot需要我们做的的工作主要就是:* 添加mybatis-spring-boot-starter依赖* 在Application上添加@MapperScan注解,并把IUser所在的包路径添加到注解中所以,我们就主要从这两面入手,来剖析下SpringBoot-Mybatis框架

3. Analyze Mybatis-spring-boot-starter Dependencies

我们在项目中引入该依赖,下面我们看下这个依赖的主要内容

<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>
<parent>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot</artifactId>
<version>1.1.1</version>
</parent>
<artifactId>mybatis-spring-boot-starter</artifactId>
<name>mybatis-spring-boot-starter</name>
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-autoconfigure</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
</project>
As you can see, the main thing is to introduce mybatis-spring-boot-autoconfigure, let's look at the structure of this jar package
Https://img-blog.csdn.net/20180803113940659?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzI2MzIzMzIz/font /5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70
The structure is simple, with a total of only three classes, and the sense that mybatisautoconfiguration should be a very important class.

在META-INF中,我们又看到熟悉的配置spring.factories,我们在这里总能发现惊喜,打开这个文件,可以看到
Auto Configure

Org.springframework.boot.autoconfigure.enableautoconfiguration=\
Org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
Again the familiar taste, Mybatisautoconfiguration was corresponded to the enableautoconfiguration, The Mybatisautoconfiguration class is then injected into the spring container when the Springboot project is started. Reasons are not mentioned here, readers can look at the author's previous blog, there are detailed introduction.

那么下面我们就来看下MybatisAutoConfiguration这个类

4. Analysis Mybatisautoconfiguration (creation of Sqlsessionfactory)

@Configuration
@ConditionalOnClass ({sqlsessionfactory.class, sqlsessionfactorybean.class}) br/> @ConditionalOnBean ( Datasource.class)
@AutoConfigureAfter (Datasourceautoconfiguration.class)
< p="">

@Beanbr/> @ConditionalOnMissingBean
The same is done with Sqlsessionfactorybean to create sqlsessionfactory
Sqlsessionfactorybean factory = new Sqlsessionfactorybean ();
Factory.setdatasource (DataSource);
FACTORY.SETVFS (Springbootvfs.class);
if (Stringutils.hastext (This.properties.getConfigLocation ())) {
Factory.setconfiglocation (This.resourceLoader.getResource (This.properties.getConfigLocation ()));
}
Factory.setconfiguration (Properties.getconfiguration ());
if (! Objectutils.isempty (this.interceptors)) {
Factory.setplugins (this.interceptors);
}
if (This.databaseidprovider! = null) {
Factory.setdatabaseidprovider (This.databaseidprovider);
}
if (Stringutils.haslength (This.properties.getTypeAliasesPackage ())) {
Factory.settypealiasespackage (This.properties.getTypeAliasesPackage ());
}
if (Stringutils.haslength (This.properties.getTypeHandlersPackage ())) {
Factory.settypehandlerspackage (This.properties.getTypeHandlersPackage ());
}
if (! Objectutils.isempty (This.properties.resolveMapperLocations ())) {
Is the mybatis.mapper-locations:classpath:mapper/*.xml we configured in the APPLICATION.YML.
Factory.setmapperlocations (This.properties.resolveMapperLocations ());
}

return factory.getObject();

}
...
@configuration annotations are added to the current class, and all of the method return values of the @bean annotations are injected into the spring container.

在这里,我们可到熟悉的SqlSessionFactory,正是Mybatis需要的组件之一,同样还是通过SqlSessionFactoryBean来创建,具体创建过程笔者不再赘述,读者可参考上一篇 Spring-Mybatis文章总结:在这里我们看到了SqlSessionFactory被注入到容器中。疑问:可以看到,创建SqlSessionFactory的方法,入参为DataSource,那么在方法调用之前,DataSource应该已经被注入到容器中了,那么DataSource是在什么时候在哪里被注入的呢?

Where is the 5.DataSource created?

我们没有主动创建DataSource的bean,那么应该也是SpringBoot帮我们主动创建了,那么究竟是在哪里创建的呢?我们可以开启日志DEBUG模式,在bean创建的过程中,都会打印相应的日志,在日志中我们搜索DataSource,可以看到以下内容

09:06:36.075 [main] DEBUG o.s.c.a.configurationclassbeandefinitionreader-registered bean definition for imported class ' Org.springframework.boot.autoconfigure.jdbc.datasourceconfiguration$tomcat '
09:06:36.075 [main] DEBUG o.s.c.a.configurationclassbeandefinitionreader-registering bean definition for @Bean method o Rg.springframework.boot.autoconfigure.jdbc.datasourceconfiguration$tomcat.datasource ()
Seen in the org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration, there was a method datasource () that was injected into the @bean, Feel this should be the way to create DataSource, we go into the class to see:

Abstract class Datasourceconfiguration {br/>..
@ConditionalOnClass (Org.apache.tomcat.jdbc.pool.DataSource.class)

static class Tomcat extends Datasourceconfiguration {

    @Bean @ConfigurationProperties (prefix = "spring.datasource.tomcat") public ORG.APACHE.TOMCAT.JDBC.POOL.DATASOURC E DataSource (datasourceproperties properties) {Org.apache.tomcat.jdbc.pool.DataSource DataSource = CRE        Atedatasource (properties, Org.apache.tomcat.jdbc.pool.DataSource.class);        Databasedriver databasedriver = databasedriver. Fromjdbcurl (Properties.determineurl ());        String validationquery = Databasedriver.getvalidationquery ();            if (validationquery! = null) {Datasource.settestonborrow (true);        Datasource.setvalidationquery (Validationquery);    } return DataSource; }} Here is really about Org.apache.tomcat.jdbc.pool.DataSource is created, and the Tomcat class also conforms to the above condition condition so the problem comes again, the current class datasourceconfiguration is just an abstract class, when was it introduced? ? After a look, we see in the Org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration class about its creation, code as follows @ Configuration@conditional (Pooleddatasourcecondition.class) @ConditionalOnMissinGBean ({datasource.class, xadatasource.class}) @Import ({DataSourceConfiguration.Tomcat.class,        DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Dbcp.class, DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.Generic.class}) @SuppressWarnings ("deprecation") protected static class Pooleddatasourceconfiguration {} Direct use of @import to introduce Datasourceconfiguration.tomcat summary: So far, we can answer the question we raised above, DataSource is injected into the spring container in the Datasourceconfiguration class; Datasourceconfiguration is injected into the spring container in the datasourceautoconfiguration.

[email protected] () Analysis of annotations (injection of Mapperfactorybean)

到目前为止,DataSource被注入到Spring中,SqlSessionFactory被注入到Spring中,还缺少MapperFactoryBean的注入我们知道在@MapperScan()注解中,我们在注解value中添加了IUser所在的包路径,直觉上,MapperFactoryBean的注入应该跟该注解有关**下面我们来看下该注解的内容:**

@Retention (retentionpolicy.runtime) br/> @Target (Elementtype.type)
@Import (Mapperscannerregistrar.class)//focus here, injected into the Mapperscannerregistrar class

1) Mapperscannerregistrar Analysis

Note that the current class implements the Importbeandefinitionregistrar interface, and there is no further discussion about the role of Importbeandefinitionregistrar,
Readers can view them on their own.
public class Mapperscannerregistrar implements Importbeandefinitionregistrar, Resourceloaderaware {

public void Registerbeandefinitions (Annotationmetadata importingclassmetadata, beandefinitionregistry registry) {

AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);...scanner.setSqlSessionTemplateBeanName(annoAttrs.getString("sqlSessionTemplateRef"));scanner.setSqlSessionFactoryBeanName(annoAttrs.getString("sqlSessionFactoryRef"));List<String> basePackages = new ArrayList<String>();for (String pkg : annoAttrs.getStringArray("value")) {  if (StringUtils.hasText(pkg)) {    basePackages.add(pkg);  }}for (String pkg : annoAttrs.getStringArray("basePackages")) {  if (StringUtils.hasText(pkg)) {    basePackages.add(pkg);  }}for (Class<?> clazz : annoAttrs.getClassArray("basePackageClasses")) {  basePackages.add(ClassUtils.getPackageName(clazz));}scanner.registerFilters();// 重点看这里,实现在ClassPathMapperScanner.doScan()scanner.doScan(StringUtils.toStringArray(basePackages));

}
}

Classpathmapperscanner.doscan ()
Public set<beandefinitionholder> Doscan (String ... basepackages) {
This method scans all classes under package path basepackages and generates Beandefinitionholder, which is injected into spring
In the current scenario, the Iuser interface is scanned and injected into spring
set<beandefinitionholder> beandefinitions = Super.doscan (basepackages);

if (beanDefinitions.isEmpty()) {  logger.warn("No MyBatis mapper was found in ‘" + Arrays.toString(basePackages) + "‘ package. Please check your configuration.");} else {  // 重要方法,下面继续观察  processBeanDefinitions(beanDefinitions);}return beanDefinitions;

}

Processbeandefinitions ()
private void Processbeandefinitions (set<beandefinitionholder> beandefinitions) {
Genericbeandefinition definition;
for (Beandefinitionholder holder:beandefinitions) {
1. Get the iuser corresponding to the Beandefinitionholder
Definition = (genericbeandefinition) holder.getbeandefinition ();

  ...  // 2.修改definition对应的Class  // 看过Spring源码的都知道,getBean()返回的就是BeanDefinitionHolder中beanClass属性对应的实例  // 所以我们后面ac.getBean(IUser.class)的返回值也就是mapperFactoryBean的实例  definition.setBeanClass(this.mapperFactoryBean.getClass());  definition.getPropertyValues().add("addToConfig", this.addToConfig);  ...  if (!explicitFactoryUsed) {    if (logger.isDebugEnabled()) {      logger.debug("Enabling autowire by type for MapperFactoryBean with name ‘" + holder.getBeanName() + "‘.");    }    definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);  }}

}
# # Summary: through the above analysis, we know that the Classpathmapperscanner.doscan () method executes, will be iuser corresponding beandefinitionholder injected into spring;

通过后续的processBeanDefinitions()方法,重新修改BeanDefinitionHolder的BeanClass属性值为mapperFactoryBean.class又是熟悉的味道,MapperFactoryBean在这里被引入,然后在真正使用到的时候被创建对应的实例,而通过对Spring-Mybatis的分析可知,MapperFactoryBean真正返回的是IUser的代理类MapperProxy
Summary:
1)DataSource在哪里被注入?    答:DataSourceAutoConfiguration类中被注入,默认值为org.apache.tomcat.jdbc.pool.DataSource2)SqlSessionFactory在哪里被注入?    答:MybatisAutoConfiguration类中被注入3)IUser等Mapper接口在哪里被注入?    答:@MapperScan注解引入的MapperScannerRegistrar中,会扫描用户给定的包路径,并将IUser对应的MapperFactoryBean注入到Spring中,真正使用IUser时,获取的MapperFactoryBean.getObject()返回值,也就是MapperProxy

Springboot-mybatis framework use and source code parsing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.