Spring Boot 集成 mybatis核心機(jī)制
Spring Boot淺析
Spring Boot 并不是對 Spring 框架的替代,而是對 Spring 的“自動配置”和“快速啟動”的封裝與增強(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>這個 starter 自動引入了:
- Spring MVC(用于 Web 開發(fā))
- Spring Core / Context(IoC 容器)
- Jackson(JSON 處理)
- Tomcat(內(nèi)嵌 Web 容器)
- 其他 Web 相關(guān)依賴
這樣開發(fā)者無需手動管理大量依賴及其版本。
2.自動配置(AutoConfiguration)
Spring Boot 通過 @EnableAutoConfiguration(通常由 @SpringBootApplication 啟用)掃描 classpath 中存在的類,自動配置 Spring 應(yīng)用上下文。
例如:
- 如果 classpath 中有
DispatcherServlet(來自 Spring Web),Spring Boot 會自動配置一個基于 Spring MVC 的 Web 應(yīng)用。 - 如果檢測到 HikariCP 和 MySQL 驅(qū)動,會自動配置數(shù)據(jù)源。
這一切都建立在 Spring 的條件化配置(@Conditional)機(jī)制之上,是 Spring Framework 本身提供的能力。
3.內(nèi)嵌容器支持
Spring Boot 內(nèi)置了 Tomcat、Jetty 或 Undertow,使得 Web 應(yīng)用可以獨(dú)立運(yùn)行(jar 包直接啟動),而不需要部署到外部 Servlet 容器。但底層處理 HTTP 請求、路由、攔截器等,依然依賴 Spring MVC。
4.Spring Boot = Spring + 約定優(yōu)于配置 + 快速啟動工具
本質(zhì)上,Spring Boot 是 Spring 生態(tài)的“腳手架”,它讓開發(fā)者能以最少的配置快速構(gòu)建生產(chǎn)級應(yīng)用,但核心功能(IoC、AOP、事務(wù)、Web 層等)仍然由 Spring Framework 提供。
- 對于 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,并自動配置DispatcherServlet、視圖解析器、消息轉(zhuǎn)換器等,使得 Web 開發(fā)極其便捷。
? 誤解澄清:
- Spring Boot 不僅限于 Web 應(yīng)用。你也可以構(gòu)建:
- 命令行應(yīng)用(無 Web)
- 消息驅(qū)動應(yīng)用(如集成 Kafka、RabbitMQ)
- 批處理應(yīng)用(配合 Spring Batch)
- 響應(yīng)式應(yīng)用(使用 WebFlux 而非 MVC)
- 在這些場景中,Spring MVC 根本不會被使用。例如:
@SpringBootApplication
public class BatchApplication {
public static void main(String[] args) {
SpringApplication.run(BatchApplication.class, args);
}
}- 這個應(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-* 依賴,每個 starter 封裝了某個功能領(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):
- 引入了對應(yīng)的 Spring 模塊(如
spring-webmvc、spring-data-jpa、spring-security-web) - 設(shè)置了兼容的版本(通過
spring-boot-dependencies管理) - 包含了自動配置類(位于
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports)
2.自動配置(AutoConfiguration)
Spring Boot 在啟動時(shí)(通過 @EnableAutoConfiguration)會掃描所有 starter 中聲明的自動配置類,并根據(jù) 條件注解(@Conditional...) 決定是否啟用。
示例:Spring Data JPA 的自動配置
當(dāng)你引入 spring-boot-starter-data-jpa 后:
- Spring Boot 檢測到 classpath 中存在
EntityManager.class和DataSource.class - 自動配置類
JpaRepositoriesAutoConfiguration被激活 - 自動創(chuàng)建
EntityManagerFactory、TransactionManager、JpaRepository實(shí)現(xiàn)等
你只需寫:
public interface UserRepository extends JpaRepository<User, Long> {}無需手動配置數(shù)據(jù)源、事務(wù)、實(shí)體管理器等。
條件化配置的關(guān)鍵注解:
@ConditionalOnClass:當(dāng) classpath 存在某類時(shí)生效@ConditionalOnMissingBean:當(dāng)容器中沒有某 Bean 時(shí)才創(chuàng)建@ConditionalOnProperty:根據(jù)配置屬性決定是否啟用
常見 Spring 模塊集成示例
| Spring 模塊 | Starter 依賴 | 自動配置效果 |
|---|---|---|
| Spring MVC | spring-boot-starter-web | 自動配置 DispatcherServlet、內(nèi)嵌 Tomcat、消息轉(zhuǎn)換器等 |
| Spring Data JPA | spring-boot-starter-data-jpa | 自動配置數(shù)據(jù)源、JPA、事務(wù)、Repository 實(shí)現(xiàn) |
| Spring Security | spring-boot-starter-security | 自動啟用安全過濾器鏈,默認(rèn)登錄頁面、CSRF 保護(hù)等 |
| Spring AOP | spring-boot-starter-aop | 自動啟用基于代理的 AOP(需配合 @EnableAspectJAutoProxy,但 Boot 通常自動處理) |
| Spring Batch | spring-boot-starter-batch | 自動配置 JobRepository、JobLauncher、數(shù)據(jù)庫 schema 初始化 |
| Spring Cache | spring-boot-starter-cache | 啟用緩存抽象,配合 @EnableCaching,可自動集成 Caffeine/Redis/Ehcache |
| Spring Integration | spring-boot-starter-integration | 自動配置消息通道、適配器等 |
自定義集成:如何集成非官方或自研模塊?
即使沒有官方 starter,也可以手動集成 Spring 模塊:
步驟:
- 引入依賴(如第三方庫或自定義 Spring 組件)
- 編寫自動配置類(可選)
- 在
application.properties中提供配置項(xiàng) - 使用
@Import或@ComponentScan加載配置
示例:手動集成 MyBatis(雖有官方 starter,但演示原理)
@Configuration
@ConditionalOnClass(SqlSessionFactory.class)
@EnableConfigurationProperties(MyBatisProperties.class)
public class MyBatisAutoConfig {
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
// 手動構(gòu)建 SqlSessionFactory
}
}然后在 resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 中注冊該配置類,即可實(shí)現(xiàn)類似 starter 的效果。
手動集成步驟詳解(無 starter)
? 目標(biāo)
不使用 mybatis-spring-boot-starter,而是通過手動配置,讓 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ū)動(以 H2 為例) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Boot JDBC(提供 DataSource 自動配置) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>?? 注意:我們只用了
spring-boot-starter-jdbc來讓 Spring Boot 自動配置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 會自動創(chuàng)建一個 DataSource Bean。
第 3 步:編寫 MyBatis 配置類(核心?。?/h3>
這是手動集成的關(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);
// 可選:注冊 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 />,自動為 @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); // 自動生成 ID
System.out.println("Inserted user ID: " + user.getId());
}
}第 6 步:啟動類
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}對比官方 Starter 做了什么?
官方 mybatis-spring-boot-starter 實(shí)際上做了以下事情:
- 引入
mybatis+mybatis-spring - 提供
MybatisProperties類綁定mybatis.*配置項(xiàng)(如mybatis.configuration.map-underscore-to-camel-case=true) - 提供自動配置類
MybatisAutoConfiguration,內(nèi)部邏輯幾乎和我們上面寫的MyBatisConfig一致 - 自動處理
MapperScannerRegistrar,支持@MapperScan或自動掃描帶@Mapper的接口
所以,手動集成 = 把 starter 的自動配置代碼自己寫一遍。
到此這篇關(guān)于Spring Boot 集成 mybatis核心機(jī)制的文章就介紹到這了,更多相關(guān)Spring Boot 集成 mybatis內(nèi)容請搜索腳本之家以前的文章或繼續(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)文章
Java?InputStream實(shí)戰(zhàn)之輕松讀取操作文件流
在Java中,輸入輸出是非常重要的基礎(chǔ)功能,其中,InputStream是Java中的一個重要輸入流類,用于從輸入源讀取數(shù)據(jù),下面我們就來學(xué)習(xí)一下InputStream類的相關(guān)知識吧2023-10-10
Spring Cloud Alibaba 之 Nacos教程詳解
Nacos是阿里的一個開源產(chǎn)品,它是針對微服務(wù)架構(gòu)中的服務(wù)發(fā)現(xiàn)、配置管理、服務(wù)治理的綜合性解決方案。這篇文章主要介紹了Spring Cloud Alibaba 之 Nacos的相關(guān)知識,需要的朋友可以參考下2020-11-11
Springboot使用thymeleaf動態(tài)模板實(shí)現(xiàn)刷新
這篇文章主要介紹了Springboot使用thymeleaf動態(tài)模板實(shí)現(xiàn)刷新,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
SpringBoot利用ThreadPoolTaskExecutor批量插入百萬級數(shù)據(jù)
在處理大量數(shù)據(jù)時(shí),為了提高效率和性能,通常需要采用批量插入的方式,本文主要介紹了SpringBoot利用ThreadPoolTaskExecutor批量插入百萬級數(shù)據(jù),具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03

