Spring Boot 集成 mybatis核心機(jī)制
Spring Boot淺析
Spring Boot 并不是對(duì) Spring 框架的替代,而是對(duì) Spring 的“自動(dòng)配置”和“快速啟動(dòng)”的封裝與增強(qiáng)。
1.依賴管理(Starter POMs)
Spring Boot 提供了一系列 spring-boot-starter-* 依賴,這些 starter 內(nèi)部已經(jīng)預(yù)定義了常用 Spring 模塊(如 Spring Core、Spring Context、Spring Web、Spring Data 等)的兼容版本。
例如:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>這個(gè) starter 自動(dòng)引入了:
- Spring MVC(用于 Web 開發(fā))
- Spring Core / Context(IoC 容器)
- Jackson(JSON 處理)
- Tomcat(內(nèi)嵌 Web 容器)
- 其他 Web 相關(guān)依賴
這樣開發(fā)者無需手動(dòng)管理大量依賴及其版本。
2.自動(dòng)配置(AutoConfiguration)
Spring Boot 通過 @EnableAutoConfiguration(通常由 @SpringBootApplication 啟用)掃描 classpath 中存在的類,自動(dòng)配置 Spring 應(yīng)用上下文。
例如:
- 如果 classpath 中有
DispatcherServlet(來自 Spring Web),Spring Boot 會(huì)自動(dòng)配置一個(gè)基于 Spring MVC 的 Web 應(yīng)用。 - 如果檢測(cè)到 HikariCP 和 MySQL 驅(qū)動(dòng),會(huì)自動(dòng)配置數(shù)據(jù)源。
這一切都建立在 Spring 的條件化配置(@Conditional)機(jī)制之上,是 Spring Framework 本身提供的能力。
3.內(nèi)嵌容器支持
Spring Boot 內(nèi)置了 Tomcat、Jetty 或 Undertow,使得 Web 應(yīng)用可以獨(dú)立運(yùn)行(jar 包直接啟動(dòng)),而不需要部署到外部 Servlet 容器。但底層處理 HTTP 請(qǐng)求、路由、攔截器等,依然依賴 Spring MVC。
4.Spring Boot = Spring + 約定優(yōu)于配置 + 快速啟動(dòng)工具
本質(zhì)上,Spring Boot 是 Spring 生態(tài)的“腳手架”,它讓開發(fā)者能以最少的配置快速構(gòu)建生產(chǎn)級(jí)應(yīng)用,但核心功能(IoC、AOP、事務(wù)、Web 層等)仍然由 Spring Framework 提供。
- 對(duì)于 Web 應(yīng)用(尤其是 REST API 或傳統(tǒng) Web 項(xiàng)目),Spring Boot 默認(rèn)使用 Spring MVC 作為 Web 層框架,因此很多人感覺“Spring Boot = Spring MVC”。
spring-boot-starter-web默認(rèn)引入 Spring MVC,并自動(dòng)配置DispatcherServlet、視圖解析器、消息轉(zhuǎn)換器等,使得 Web 開發(fā)極其便捷。
? 誤解澄清:
- Spring Boot 不僅限于 Web 應(yīng)用。你也可以構(gòu)建:
- 命令行應(yīng)用(無 Web)
- 消息驅(qū)動(dòng)應(yīng)用(如集成 Kafka、RabbitMQ)
- 批處理應(yīng)用(配合 Spring Batch)
- 響應(yīng)式應(yīng)用(使用 WebFlux 而非 MVC)
- 在這些場(chǎng)景中,Spring MVC 根本不會(huì)被使用。例如:
@SpringBootApplication
public class BatchApplication {
public static void main(String[] args) {
SpringApplication.run(BatchApplication.class, args);
}
}- 這個(gè)應(yīng)用可能只用到 Spring Core、Spring Batch,完全不涉及 MVC。
?? 更準(zhǔn)確的說法:
Spring Boot 的核心是 Spring Framework,而 Spring MVC 是其在構(gòu)建 Web 應(yīng)用時(shí)默認(rèn)采用的 Web 層實(shí)現(xiàn)。
核心機(jī)制:Starter + AutoConfiguration
1.Starter 依賴(約定優(yōu)于配置)
Spring Boot 提供了一系列 spring-boot-starter-* 依賴,每個(gè) starter 封裝了某個(gè)功能領(lǐng)域所需的全部依賴。
例如:
<!-- Web 應(yīng)用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 數(shù)據(jù)訪問(JPA) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 安全控制 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>這些 starter 內(nèi)部已經(jīng):
- 引入了對(duì)應(yīng)的 Spring 模塊(如
spring-webmvc、spring-data-jpa、spring-security-web) - 設(shè)置了兼容的版本(通過
spring-boot-dependencies管理) - 包含了自動(dòng)配置類(位于
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports)
2.自動(dòng)配置(AutoConfiguration)
Spring Boot 在啟動(dòng)時(shí)(通過 @EnableAutoConfiguration)會(huì)掃描所有 starter 中聲明的自動(dòng)配置類,并根據(jù) 條件注解(@Conditional...) 決定是否啟用。
示例:Spring Data JPA 的自動(dòng)配置
當(dāng)你引入 spring-boot-starter-data-jpa 后:
- Spring Boot 檢測(cè)到 classpath 中存在
EntityManager.class和DataSource.class - 自動(dòng)配置類
JpaRepositoriesAutoConfiguration被激活 - 自動(dòng)創(chuàng)建
EntityManagerFactory、TransactionManager、JpaRepository實(shí)現(xiàn)等
你只需寫:
public interface UserRepository extends JpaRepository<User, Long> {}無需手動(dòng)配置數(shù)據(jù)源、事務(wù)、實(shí)體管理器等。
條件化配置的關(guān)鍵注解:
@ConditionalOnClass:當(dāng) classpath 存在某類時(shí)生效@ConditionalOnMissingBean:當(dāng)容器中沒有某 Bean 時(shí)才創(chuàng)建@ConditionalOnProperty:根據(jù)配置屬性決定是否啟用
常見 Spring 模塊集成示例
| Spring 模塊 | Starter 依賴 | 自動(dòng)配置效果 |
|---|---|---|
| Spring MVC | spring-boot-starter-web | 自動(dòng)配置 DispatcherServlet、內(nèi)嵌 Tomcat、消息轉(zhuǎn)換器等 |
| Spring Data JPA | spring-boot-starter-data-jpa | 自動(dòng)配置數(shù)據(jù)源、JPA、事務(wù)、Repository 實(shí)現(xiàn) |
| Spring Security | spring-boot-starter-security | 自動(dòng)啟用安全過濾器鏈,默認(rèn)登錄頁面、CSRF 保護(hù)等 |
| Spring AOP | spring-boot-starter-aop | 自動(dòng)啟用基于代理的 AOP(需配合 @EnableAspectJAutoProxy,但 Boot 通常自動(dòng)處理) |
| Spring Batch | spring-boot-starter-batch | 自動(dòng)配置 JobRepository、JobLauncher、數(shù)據(jù)庫 schema 初始化 |
| Spring Cache | spring-boot-starter-cache | 啟用緩存抽象,配合 @EnableCaching,可自動(dòng)集成 Caffeine/Redis/Ehcache |
| Spring Integration | spring-boot-starter-integration | 自動(dòng)配置消息通道、適配器等 |
自定義集成:如何集成非官方或自研模塊?
即使沒有官方 starter,也可以手動(dòng)集成 Spring 模塊:
步驟:
- 引入依賴(如第三方庫或自定義 Spring 組件)
- 編寫自動(dòng)配置類(可選)
- 在
application.properties中提供配置項(xiàng) - 使用
@Import或@ComponentScan加載配置
示例:手動(dòng)集成 MyBatis(雖有官方 starter,但演示原理)
@Configuration
@ConditionalOnClass(SqlSessionFactory.class)
@EnableConfigurationProperties(MyBatisProperties.class)
public class MyBatisAutoConfig {
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
// 手動(dòng)構(gòu)建 SqlSessionFactory
}
}然后在 resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 中注冊(cè)該配置類,即可實(shí)現(xiàn)類似 starter 的效果。
手動(dòng)集成步驟詳解(無 starter)
? 目標(biāo)
不使用 mybatis-spring-boot-starter,而是通過手動(dòng)配置,讓 MyBatis 在 Spring Boot 中正常工作。
第 1 步:添加依賴
在 pom.xml 中引入必要依賴(注意:不引入 starter):
<!-- MyBatis 核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<!-- MyBatis 與 Spring 集成橋接 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
<!-- 數(shù)據(jù)庫驅(qū)動(dòng)(以 H2 為例) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Boot JDBC(提供 DataSource 自動(dòng)配置) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>?? 注意:我們只用了
spring-boot-starter-jdbc來讓 Spring Boot 自動(dòng)配置DataSource,但沒有用 MyBatis 的 starter。
第 2 步:配置數(shù)據(jù)源(application.yml)
spring:
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password: ''Spring Boot 會(huì)自動(dòng)創(chuàng)建一個(gè) DataSource Bean。
第 3 步:編寫 MyBatis 配置類(核心?。?/h3>
這是手動(dòng)集成的關(guān)鍵:用 Java Config 替代 XML 配置。
@Configuration
@MapperScan(basePackages = "com.example.demo.mapper") // 掃描 Mapper 接口
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
// 可選:設(shè)置 MyBatis 全局配置(如駝峰映射)
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setMapUnderscoreToCamelCase(true);
factoryBean.setConfiguration(configuration);
// 可選:注冊(cè) Mapper XML 文件位置
// factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
// .getResources("classpath:mapper/*.xml"));
return factoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}關(guān)鍵點(diǎn)解析:
| 組件 | 作用 |
|---|---|
@MapperScan | 等價(jià)于 XML 中的 <mybatis:scan />,自動(dòng)為 @Mapper 接口生成代理 Bean |
SqlSessionFactoryBean | Spring FactoryBean,用于創(chuàng)建 SqlSessionFactory |
PlatformTransactionManager | 啟用 Spring 管理的事務(wù)(配合 @Transactional) |
?? 注意:
SqlSessionFactoryBean是FactoryBean<SqlSessionFactory>,調(diào)用.getObject()才得到真正的SqlSessionFactory。
第 4 步:編寫 Mapper 接口和實(shí)體類
// 實(shí)體類
public class User {
private Long id;
private String name;
// getter/setter
}
// Mapper 接口
@Mapper // 可省略,因?yàn)?@MapperScan 已覆蓋
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(Long id);
@Insert("INSERT INTO user(name) VALUES(#{name})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insert(User user);
}如果使用 XML 映射文件,需在
SqlSessionFactory中通過setMapperLocations()指定路徑。
第 5 步:在 Service 中使用
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional
public void createUser(String name) {
User user = new User();
user.setName(name);
userMapper.insert(user); // 自動(dòng)生成 ID
System.out.println("Inserted user ID: " + user.getId());
}
}第 6 步:啟動(dòng)類
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}對(duì)比官方 Starter 做了什么?
官方 mybatis-spring-boot-starter 實(shí)際上做了以下事情:
- 引入
mybatis+mybatis-spring - 提供
MybatisProperties類綁定mybatis.*配置項(xiàng)(如mybatis.configuration.map-underscore-to-camel-case=true) - 提供自動(dòng)配置類
MybatisAutoConfiguration,內(nèi)部邏輯幾乎和我們上面寫的MyBatisConfig一致 - 自動(dòng)處理
MapperScannerRegistrar,支持@MapperScan或自動(dòng)掃描帶@Mapper的接口
所以,手動(dòng)集成 = 把 starter 的自動(dòng)配置代碼自己寫一遍。
到此這篇關(guān)于Spring Boot 集成 mybatis核心機(jī)制的文章就介紹到這了,更多相關(guān)Spring Boot 集成 mybatis內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot集成MyBatis實(shí)現(xiàn)SQL攔截器的實(shí)戰(zhàn)指南
- SpringBoot集成MyBatis中SQL攔截器的實(shí)戰(zhàn)指南
- SpringBoot+MyBatis集成微信支付實(shí)現(xiàn)示例
- SpringBoot +MybatisPlus集成多數(shù)據(jù)源的使用案例
- springboot集成Mybatis-plus-join-boot-start詳解
- SpringBoot同時(shí)集成Mybatis和Mybatis-plus框架
- SpringBoot與MyBatis-Plus的高效集成方式
- Maven構(gòu)建SpringBoot集成MyBatis過程
- springboot集成mybatis-plus全過程
相關(guān)文章
為什么ConcurrentHashMap的key value不能為null,map可以?
這篇文章主要介紹了為什么ConcurrentHashMap的key value不能為null,map可以呢?具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-01-01
深入理解SpringMVC中央調(diào)度器DispatcherServlet
這篇文章主要介紹了SpringMVC核心之中央調(diào)度器DispatcherServlet的相關(guān)知識(shí),包括SpringMVC請(qǐng)求處理過程及SrpingMVC容器和spring?IOC容器關(guān)系,需要的朋友可以參考下2022-05-05
SpringBoot注解@EnableScheduling定時(shí)任務(wù)詳細(xì)解析
這篇文章主要介紹了SpringBoot注解@EnableScheduling定時(shí)任務(wù)詳細(xì)解析,@EnableScheduling 開啟對(duì)定時(shí)任務(wù)的支持,啟動(dòng)類里面使用@EnableScheduling 注解開啟功能,自動(dòng)掃描,需要的朋友可以參考下2024-01-01
解決springboot項(xiàng)目啟動(dòng)報(bào)錯(cuò)Field xxxMapper in com...xx
這篇文章主要介紹了解決springboot項(xiàng)目啟動(dòng)報(bào)錯(cuò)Field xxxMapper in com...xxxContr問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
SpringBoot?Profile多環(huán)境配置方式
這篇文章主要介紹了SpringBoot?Profile多環(huán)境配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
springboot項(xiàng)目攔截前端請(qǐng)求中的特殊字符串(解決方案)
springboot項(xiàng)目中,需要對(duì)前端請(qǐng)求數(shù)據(jù)進(jìn)行過濾,攔截特殊字符,本文通過實(shí)例代碼給大家分享完美解決方案,感興趣的朋友一起看看吧2023-10-10

