第一步,准备好jar包
除了Spring最基本的6个jar包:
-
spring-aop.jar 开发AOP特性时需要的JAR
-
spring-beans.jar 处理Bean的jar
<bean>
-
spring-context.jar 处理spring上下文的jar
<context>
-
spring-core.jar spring核心jar
-
spring-expression.jar spring表达式
-
commons-logging.jar 第三方日志
还需要:
- spring-tx-4.3.9.RELEASE
- mysql-connector-java-8.0.15.jar 数据库驱动
- commons-dbcp.jar 连接池使用到数据源
- commons-pool.jar 连接池
- spring-jdbc-4.3.9.RELEASE.jar
- aopalliance.jar
黏贴到src目录下,右键- bulid path即可。
第二步,配置
首先要 添加 tx 命名空间,在下载完STS插件后,点击tx即可
添加后开始配置:
思路:
首先配这个:
<!-- 增加对事务的支持 tx命名空间-->
<tx:annotation-driven transaction-manager="txManager"/>
发现它需要配置一个txManager,于是配置txManager:
<!-- 配置事务管理器 txManager -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">
</property>
</bean>
配置txManager需要一个dataSource,所以我们还要配置一个:
<!-- 配置数据库相关 事务 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/db_stu?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai"></property>
<property name="username" value="root" ></property>
<property name="password" value="root"></property>
<property name="maxActive" value="10" ></property>
<property name="maxIdle" value="6"></property>
</bean>
这样就把思路理清了,总的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 配置数据库相关 事务 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/db_stu?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai"></property>
<property name="username" value="root" ></property>
<property name="password" value="root"></property>
<property name="maxActive" value="10" ></property>
<property name="maxIdle" value="6"></property>
</bean>
<!-- 配置事务管理器 txManager -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">
</property>
</bean>
<!-- 增加对事务的支持 tx命名空间-->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
最后一步,使用注解
在需要添加事务控制的地方,写上: @Transactional
这里引用一些其他博主写的博客