注解配置事务就很简单了
我们只需要激活@Transactional注解就可以了
然后在需要的事务前面加上@Transactional注解就可以了
我们需要在配置文件中引入tx命名空间
xmlns:tx="http://www.springframework.org/schema/tx"
和
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd"
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="jee.pk3"></context:component-scan>
<!-- 引入jdbc.properties -->
<context:property-placeholder location="jdbc.properties"/>
<!-- 配置dbcp数据库 -->
<bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${url}" />
<property name="username" value="${uName}" />
<property name="password" value="${password}" />
<property name="initialSize" value="3" />
</bean>
<!-- 事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 激活@Transactional注解,始终使用cglib动态代理 -->
<tx:annotation-driven proxy-target-class="true"/>
</beans>
需要事务的类
package jee.pk3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
@Component("userService")
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
//参数为配置文件中事务管理器的名字,默认使用id=transactionManager 的事务管理器
@Transactional(transactionManager = "txManager")//此方法在事务中执行
public void remove() {
userDao.delete(3);
if(1==1)
{
throw new RuntimeException("某个错误");
}
userDao.delete(2);
}
}