項目結構
spring4-mybatis3
├── src/main/java
│ ├── me.gacl.domain → 實體類
│ ├── me.gacl.dao → Mapper 接口
│ ├── me.gacl.mapping → Mapper XML
│ ├── me.gacl.service → Service 接口
│ ├── me.gacl.service.impl→ Service 實現
│ └── me.gacl.web.controller → Servlet 控制器
├── src/main/resources
│ ├── dbconfig.properties → 數據源配置
│ ├── spring.xml → Spring 核心配置
│ └── spring-mybatis.xml → 整合配置
└── src/main/webapp
├── WEB-INF/web.xml
└── index.jsp
Maven 依賴管理
<properties>
<spring.version>4.3.30.RELEASE</spring.version>
<mybatis.version>3.5.13</mybatis.version>
<mybatis-spring.version>2.0.7</mybatis-spring.version>
</properties>
<dependencies>
<!-- Spring 核心 -->
<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${spring.version}</version></dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version><scope>test</scope></dependency>
<!-- MyBatis -->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency>
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>${mybatis-spring.version}</version></dependency>
<!-- 數據庫與連接池 -->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.18</version></dependency>
<!-- Web 支持 -->
<dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope></dependency>
<dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency>
<!-- 測試 -->
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency>
</dependencies>
核心配置文件
dbconfig.properties
driverClassName=com.mysql.cj.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/spring4_mybatis3?useSSL=false&serverTimezone=UTC
jdbc_username=root
jdbc_password=123456
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:dbconfig.properties"/>
<context:component-scan base-package="me.gacl.service"/>
</beans>
spring-mybatis.xml(整合核心)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:tx="https://www.springframework.org/schema/tx"
xmlns:aop="https://www.springframework.org/schema/aop"
xsi:schemaLocation="...spring-beans.xsd ...spring-tx.xsd ...spring-aop.xsd">
<!-- 1. Druid 數據源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_username}"/>
<property name="password" value="${jdbc_password}"/>
<property name="initialSize" value="5"/>
<property name="maxActive" value="20"/>
<property name="validationQuery" value="${validationQuery}"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<property name="filters" value="stat"/>
</bean>
<!-- 2. SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:me/gacl/mapping/*.xml"/>
<property name="typeAliasesPackage" value="me.gacl.domain"/>
</bean>
<!-- 3. Mapper 掃描器(自動生成 Mapper 代理) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="me.gacl.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 4. 事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 5. AOP 事務增強 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="*" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="serviceMethods" expression="execution(* me.gacl.service..*Impl.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
</aop:config>
<!-- 6. Druid 監控 Spring JDBC -->
<bean id="druidStatInterceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"/>
<bean id="druidStatPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
<property name="patterns"><value>me.gacl.service.*</value></property>
</bean>
<aop:config>
<aop:advisor advice-ref="druidStatInterceptor" pointcut-ref="druidStatPointcut"/>
</aop:config>
</beans>
業務代碼實現
// UserMapper.java(無需實現類)
public interface UserMapper {
List<User> getAllUser();
User selectByPrimaryKey(String id);
int insert(User user);
}
// UserServiceImpl.java
@Service("userService")
public class UserServiceImpl implements UserServiceI {
@Autowired private UserMapper userMapper;
public List<User> getAllUser() { return userMapper.getAllUser(); }
public User getUserById(String id) { return userMapper.selectByPrimaryKey(id); }
public void addUser(User user) { userMapper.insert(user); }
}
// UserServlet.java
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
private UserServiceI userService;
public void init() {
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
userService = (UserServiceI) ac.getBean("userService");
}
protected void doGet(req, resp) {
req.setAttribute("lstUsers", userService.getAllUser());
req.getRequestDispatcher("/index.jsp").forward(req, resp);
}
}
web.xml 整合入口
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
</context-param>
Maven 編譯部署避坑
mvn clean compile war:war 打包
- 部署至 Tomcat 8.5+(Servlet 3.0 支持 @WebServlet)
- 若
mvn install 失敗:嘗試 Maven Clean → Project Clean → Maven Install