首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

SpringMVC4 + Spring + MyBatis3 全註解極簡整合實戰指南

     編輯:Java 綜合教學

SpringMVC4 + Spring + MyBatis3 全註解極簡整合實戰指南

本文基於 Spring 4.1.5、MyBatis 3,採用全註解配置方式,逐步構建一個乾淨、可維護的企業級應用基礎架構。涵蓋 web.xml、SpringMVC、Spring 業務層、MyBatis、多數據源及代碼生成器配置,適合快速啟動新專案。

一、web.xml:雙容器啟動機制

配置兩大核心組件:

  • DispatcherServlet:SpringMVC 前端控制器,`load-on-startup=1` 隨容器啟動,`init-param` 指定 `spring-mvc.xml`。
  • ContextLoaderListener:Spring 根容器啟動監聽器,`context-param` 指定 `applicationContext.xml`。

關鍵區別:`init-param` 針對單個 Servlet,`context-param` 作用於整個 Web 應用。

二、spring-mvc.xml:專注 Web 層

<mvc:annotation-driven />
<context:component-scan base-package="net.aazj.controller" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/" />
    <property name="suffix" value=".jsp" />
</bean>

避坑指南:SpringMVC 與 Spring 的 `component-scan` 必須隔離——前者只掃描 `@Controller`,後者只掃描 `@Service`/`@Repository`。交叉掃描會導致事務失效。若必須共用基包,請用 `exclude-filter` 排除對方註解類型。

三、applicationContext.xml:業務層與持久層整合

<context:component-scan base-package="net.aazj.service" />
<context:property-placeholder location="classpath:config/db.properties" />

<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" ... />

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:config/mybatis-config.xml" />
    <property name="mapperLocations" value="classpath*:config/mappers/**/*.xml" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="net.aazj.mapper" />
</bean>

要點:`MapperScannerConfigurer` 自動將 Mapper 接口註冊為 Bean,Service 中直接 `@Autowired` 注入;事務由 `@Transactional` 驅動。

四、mybatis-config.xml:按需配置

僅在需自定義 ``、`` 時提供。示例啟用緩存、延遲載入、駝峰映射等,並為 POJO 定義別名(如 `@Alias("User")`),Mapper XML 中直接使用別名 `resultType="User"`。

五、generatorConfig.xml:MyBatis Generator 逆向工程

配置要點:

  • `classPathEntry`:指定 JDBC 驅動路徑。
  • `jdbcConnection`:資料庫連線資訊。
  • `javaModelGenerator`/`sqlMapGenerator`/`javaClientGenerator`:分別指定 POJO、Mapper XML、Mapper 接口生成目錄。
  • `table`:指定處理的表、`generatedKey` 設定自增主鍵策略。

六、多數據源擴展:讀寫分離實戰

核心思路:配置兩套 `dataSource`、`sqlSessionFactory`、`transactionManager`、`MapperScannerConfigurer`,關鍵在於 `MapperScannerConfigurer` 中指定 `sqlSessionFactoryBeanName`,使不同包下的 Mapper 綁定對應會話工廠。Service 層透過 `@Autowired` 自動注入正確的 Mapper。

總結

全註解配置大幅減少 XML 開銷,結合包隔離掃描、屬性佔位符、Druid 連接池、MyBatis Generator,構建出結構清晰、易於擴展的標準化專案骨架。實際專案中可按模組劃分包結構,進一步提升維護性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved