最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Boot 集成 mybatis核心機制

 更新時間:2025年11月26日 10:58:48   作者:chxii  
這篇文章給大家介紹Spring Boot 集成 mybatis核心機制,本文結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧

Spring Boot淺析

Spring Boot 并不是對 Spring 框架的替代,而是對 Spring 的“自動配置”和“快速啟動”的封裝與增強。

1.依賴管理(Starter POMs)

Spring Boot 提供了一系列 spring-boot-starter-* 依賴,這些 starter 內部已經預定義了常用 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(內嵌 Web 容器)
  • 其他 Web 相關依賴

這樣開發(fā)者無需手動管理大量依賴及其版本。

2.自動配置(AutoConfiguration)

Spring Boot 通過 @EnableAutoConfiguration(通常由 @SpringBootApplication 啟用)掃描 classpath 中存在的類,自動配置 Spring 應用上下文。

例如:

  • 如果 classpath 中有 DispatcherServlet(來自 Spring Web),Spring Boot 會自動配置一個基于 Spring MVC 的 Web 應用。
  • 如果檢測到 HikariCP 和 MySQL 驅動,會自動配置數據源。

這一切都建立在 Spring 的條件化配置(@Conditional)機制之上,是 Spring Framework 本身提供的能力。

3.內嵌容器支持

Spring Boot 內置了 Tomcat、Jetty 或 Undertow,使得 Web 應用可以獨立運行(jar 包直接啟動),而不需要部署到外部 Servlet 容器。但底層處理 HTTP 請求、路由、攔截器等,依然依賴 Spring MVC

4.Spring Boot = Spring + 約定優(yōu)于配置 + 快速啟動工具

本質上,Spring Boot 是 Spring 生態(tài)的“腳手架”,它讓開發(fā)者能以最少的配置快速構建生產級應用,但核心功能(IoC、AOP、事務、Web 層等)仍然由 Spring Framework 提供。

  • 對于 Web 應用(尤其是 REST API 或傳統(tǒng) Web 項目),Spring Boot 默認使用 Spring MVC 作為 Web 層框架,因此很多人感覺“Spring Boot = Spring MVC”。
  • spring-boot-starter-web 默認引入 Spring MVC,并自動配置 DispatcherServlet、視圖解析器、消息轉換器等,使得 Web 開發(fā)極其便捷。

? 誤解澄清:

  • Spring Boot 不僅限于 Web 應用。你也可以構建:
  • 命令行應用(無 Web)
  • 消息驅動應用(如集成 Kafka、RabbitMQ)
  • 批處理應用(配合 Spring Batch)
  • 響應式應用(使用 WebFlux 而非 MVC)
  • 在這些場景中,Spring MVC 根本不會被使用。例如:
@SpringBootApplication
public class BatchApplication {
    public static void main(String[] args) {
        SpringApplication.run(BatchApplication.class, args);
    }
}
  • 這個應用可能只用到 Spring Core、Spring Batch,完全不涉及 MVC。

?? 更準確的說法:

Spring Boot 的核心是 Spring Framework,而 Spring MVC 是其在構建 Web 應用時默認采用的 Web 層實現。

核心機制:Starter + AutoConfiguration

1.Starter 依賴(約定優(yōu)于配置)

Spring Boot 提供了一系列 spring-boot-starter-* 依賴,每個 starter 封裝了某個功能領域所需的全部依賴。

例如:

<!-- Web 應用 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 數據訪問(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 內部已經:

  • 引入了對應的 Spring 模塊(如 spring-webmvc、spring-data-jpa、spring-security-web
  • 設置了兼容的版本(通過 spring-boot-dependencies 管理)
  • 包含了自動配置類(位于 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

2.自動配置(AutoConfiguration)

Spring Boot 在啟動時(通過 @EnableAutoConfiguration)會掃描所有 starter 中聲明的自動配置類,并根據 條件注解(@Conditional...) 決定是否啟用。

示例:Spring Data JPA 的自動配置

當你引入 spring-boot-starter-data-jpa 后:

  • Spring Boot 檢測到 classpath 中存在 EntityManager.class 和 DataSource.class
  • 自動配置類 JpaRepositoriesAutoConfiguration 被激活
  • 自動創(chuàng)建 EntityManagerFactory、TransactionManager、JpaRepository 實現等

你只需寫:

public interface UserRepository extends JpaRepository<User, Long> {}

無需手動配置數據源、事務、實體管理器等。

條件化配置的關鍵注解:

  • @ConditionalOnClass:當 classpath 存在某類時生效
  • @ConditionalOnMissingBean:當容器中沒有某 Bean 時才創(chuàng)建
  • @ConditionalOnProperty:根據配置屬性決定是否啟用

常見 Spring 模塊集成示例

Spring 模塊Starter 依賴自動配置效果
Spring MVCspring-boot-starter-web自動配置 DispatcherServlet、內嵌 Tomcat、消息轉換器等
Spring Data JPAspring-boot-starter-data-jpa自動配置數據源、JPA、事務、Repository 實現
Spring Securityspring-boot-starter-security自動啟用安全過濾器鏈,默認登錄頁面、CSRF 保護等
Spring AOPspring-boot-starter-aop自動啟用基于代理的 AOP(需配合 @EnableAspectJAutoProxy,但 Boot 通常自動處理)
Spring Batchspring-boot-starter-batch自動配置 JobRepository、JobLauncher、數據庫 schema 初始化
Spring Cachespring-boot-starter-cache啟用緩存抽象,配合 @EnableCaching,可自動集成 Caffeine/Redis/Ehcache
Spring Integrationspring-boot-starter-integration自動配置消息通道、適配器等

自定義集成:如何集成非官方或自研模塊?

即使沒有官方 starter,也可以手動集成 Spring 模塊:

步驟:

  1. 引入依賴(如第三方庫或自定義 Spring 組件)
  2. 編寫自動配置類(可選)
  3. 在 application.properties 中提供配置項
  4. 使用 @Import 或 @ComponentScan 加載配置

示例:手動集成 MyBatis(雖有官方 starter,但演示原理)

@Configuration
@ConditionalOnClass(SqlSessionFactory.class)
@EnableConfigurationProperties(MyBatisProperties.class)
public class MyBatisAutoConfig {
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
        // 手動構建 SqlSessionFactory
    }
}

然后在 resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 中注冊該配置類,即可實現類似 starter 的效果。

手動集成步驟詳解(無 starter)

? 目標

不使用 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>
<!-- 數據庫驅動(以 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 步:配置數據源(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 配置類(核心!)

這是手動集成的關鍵:用 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);
        // 可選:設置 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);
    }
}

關鍵點解析:

組件作用
@MapperScan等價于 XML 中的 <mybatis:scan />,自動為 @Mapper 接口生成代理 Bean
SqlSessionFactoryBeanSpring FactoryBean,用于創(chuàng)建 SqlSessionFactory
PlatformTransactionManager啟用 Spring 管理的事務(配合 @Transactional

?? 注意:SqlSessionFactoryBeanFactoryBean<SqlSessionFactory>,調用 .getObject() 才得到真正的 SqlSessionFactory

第 4 步:編寫 Mapper 接口和實體類

// 實體類
public class User {
    private Long id;
    private String name;
    // getter/setter
}
// Mapper 接口
@Mapper // 可省略,因為 @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 實際上做了以下事情:

  1. 引入 mybatis + mybatis-spring
  2. 提供 MybatisProperties 類綁定 mybatis.* 配置項(如 mybatis.configuration.map-underscore-to-camel-case=true
  3. 提供自動配置類 MybatisAutoConfiguration,內部邏輯幾乎和我們上面寫的 MyBatisConfig 一致
  4. 自動處理 MapperScannerRegistrar,支持 @MapperScan 或自動掃描帶 @Mapper 的接口

所以,手動集成 = 把 starter 的自動配置代碼自己寫一遍

到此這篇關于Spring Boot 集成 mybatis核心機制的文章就介紹到這了,更多相關Spring Boot 集成 mybatis內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 為什么ConcurrentHashMap的key value不能為null,map可以?

    為什么ConcurrentHashMap的key value不能為null,map可以?

    這篇文章主要介紹了為什么ConcurrentHashMap的key value不能為null,map可以呢?具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01
  • 深入理解SpringMVC中央調度器DispatcherServlet

    深入理解SpringMVC中央調度器DispatcherServlet

    這篇文章主要介紹了SpringMVC核心之中央調度器DispatcherServlet的相關知識,包括SpringMVC請求處理過程及SrpingMVC容器和spring?IOC容器關系,需要的朋友可以參考下
    2022-05-05
  • Java如何獲取靜態(tài)資源文件路徑

    Java如何獲取靜態(tài)資源文件路徑

    這篇文章主要介紹了Java如何獲取靜態(tài)資源文件路徑問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • 詳解Java如何跨平臺獲取MAC地址

    詳解Java如何跨平臺獲取MAC地址

    有時我們因為軟件授權或者其它需要獲取主機唯一標識而需要獲取用戶主機的MAC地址,而本文則將介紹如何通過Java來實現跨平臺獲取MAC地址的兩種方法,需要的朋友可以參考下
    2021-06-06
  • SpringBoot注解@EnableScheduling定時任務詳細解析

    SpringBoot注解@EnableScheduling定時任務詳細解析

    這篇文章主要介紹了SpringBoot注解@EnableScheduling定時任務詳細解析,@EnableScheduling 開啟對定時任務的支持,啟動類里面使用@EnableScheduling 注解開啟功能,自動掃描,需要的朋友可以參考下
    2024-01-01
  • 解決springboot項目啟動報錯Field xxxMapper in com...xxxController required

    解決springboot項目啟動報錯Field xxxMapper in com...xx

    這篇文章主要介紹了解決springboot項目啟動報錯Field xxxMapper in com...xxxContr問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • SpringBoot?Profile多環(huán)境配置方式

    SpringBoot?Profile多環(huán)境配置方式

    這篇文章主要介紹了SpringBoot?Profile多環(huán)境配置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • springboot項目攔截前端請求中的特殊字符串(解決方案)

    springboot項目攔截前端請求中的特殊字符串(解決方案)

    springboot項目中,需要對前端請求數據進行過濾,攔截特殊字符,本文通過實例代碼給大家分享完美解決方案,感興趣的朋友一起看看吧
    2023-10-10
  • 淺談Java中類的實例化步驟

    淺談Java中類的實例化步驟

    今天小編就為大家分享一篇關于淺談Java中類的實例化步驟,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-02-02
  • Java程序執(zhí)行cmd命令全過程

    Java程序執(zhí)行cmd命令全過程

    這篇文章主要介紹了Java程序執(zhí)行cmd命令全過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01

最新評論

尚义县| 河曲县| 阳春市| 许昌市| 延川县| 蕲春县| 沙洋县| 临夏县| 农安县| 大兴区| 汉中市| 进贤县| 铜川市| 云南省| 镇远县| 元氏县| 苗栗县| 芦溪县| 长春市| 巩留县| 青冈县| 江陵县| 浪卡子县| 溧阳市| 二连浩特市| 砚山县| 馆陶县| 深水埗区| 洞头县| 轮台县| 太保市| 江口县| 开封县| 犍为县| 曲沃县| 广西| 凤凰县| 扶余县| 柳江县| 舞阳县| 平乐县|