Spring Boot 思想
Spring Boot 是 Spring 提供的一个快速开发工具包,让程序员更方便、更快捷的开发Spring应用。提出了约定大于配置和自动装配的思想。通过starter机制整合了一系列的框架,开发者只需要添加对starter的依赖,通过简单的配置,即可完成对框架的整合。
Spring Boot 使用
整合MyBatis的为例
第一步:在pom中添加MyBatis的starter
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
第二步:在application.yml文件中添加配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/blog_test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
username: root
password: 123456
mybatis:
# 指定mapper文件的路径
mapper-locations: classpath:mapper/*.xml
# 指定实体类的路径
type-aliases-package: com.learn.blog.demo.entity
configuration:
# 开启驼峰命名
map-underscore-to-camel-case: true
以上两步即可完成对MyBatis的整合。相对于传统的 Spring 项目简化了许多配置,这就是Spring Boot的自动装配带来的便利。
Spring Boot自动装配原理
Spring Boot 的自动装配依赖于 Spring 推出了JavaConfig 的配置模式,开发者可以通过@Configuration + @Bean 的方式向 Spring IOC 容器注入 Bean。
每个 starter 都有自己的 JavaConfig 配置类,在 starter 的META-INF/spring.factories文件中配置了这个类的全路径,Spring Boot 通过这个读取这个文件,获取到starter的配置类路径,然后加载到IOC 容器中,从而完成starter的自动装配。
Spring Boot 启动时会通过SPI机制查找JavaConfig,下面我们来从Spring Boot 的启动类上的@SpringBootApplication 入手,一探究竟。
package com.learn.blog.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BlogDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BlogDemoApplication.class, args);
}
}
当我们点进 @SpringBootApplication 看时,发现它是个复合注解
接下来进入 @EnableAutoConfiguration ,我们会发现里面通过 @Import 导入了一个类 AutoConfigurationImportSelector.class
继续追踪AutoConfigurationImportSelector.class,Spring Boot启动会回调selectImports方法
在selectImports方法中调用了getAutoConfigurationEntry方法
在 getAutoConfigurationEntry方法中又调用了getCandidateConfigurations方法,方法中SpringFactoriesLoader.loadFactoryNames 去加载 META-INF/spring.factories 文件,从而获取starter的自动配置类路径,加载到 IOC 容器完成自动装配。
展示下MyBatis的starter里面配置
spring.factories
MyBatis的两个配置类