spring基于纯注解的声明式事务控制(*)
了解即可,真实项目中不建议使用这种方式
一、纯注解配置步骤
1). 配置数据库连接信息jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_01
jdbc.username=root
jdbc.password=abc123
2). 配置jdbcConfig jdbcTemplate与数据源
DataSourceTransactionManager类中有个属性nestedTransactionAllowed ,表示允许【嵌套事务】,基于此原理,然后再基于切面编程(被代理方法前后增强),实现嵌套事务!
package config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
/**
* 和连接数据库相关的配置类
*/
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name = "jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name="dataSource")
public DataSource createDataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
3). 配置 事务管理器TransactionConfig --- 切面
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
/**
* 和事务相关的配置类
*/
public class TransactionConfig {
/** 创建事务管理器对象 */
@Bean(name="transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
4). 配置综合配置类SpringConfiguration
相当于applicationContext.xml;其中@EnableTransactionManagement表示开启事务
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* spring的配置类,相当于applicationContext.xml
*/
@Configuration
@ComponentScan("com.itheima")
@Import({JdbcConfig.class,TransactionConfig.class})
@PropertySource("jdbcConfig.properties")
@EnableTransactionManagement // 开启事务
public class SpringConfiguration {
}
二、项目其他源代码
1). 项目结构
2). Account pojo
省略get/set/toString方法
public class Account {
private Integer id;
private String name;
private Float money;
...
3). MyJdbcDaoSupport 抽离的jdbcTemplate
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
/** 如果使用注解开发,需要自己抽离JdbcTemplate */
@Component("myJdbcDaoSupport")
public class MyJdbcDaoSupport {
// 下面这部分就需要在配置文件中进行配置
@Autowired
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
}
4). dao持久层
import com.itheima.domain.Account;
import java.sql.SQLException;
public interface AccountDao {
/** 根据id查询账户的余额 */
public Account queryMoney(Integer id) throws SQLException;
/** 根据id更新账户的余额 */
public int updateMoney(Integer id, Float money) throws SQLException;
}
import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.utils.MyJdbcDaoSupport;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
@Repository("accountDao")
public class AccountDaoImpl extends MyJdbcDaoSupport implements AccountDao {
/** @事务
* 根据id查询账户的余额,将异常显示抛出 */
@Override
public Account queryMoney(Integer id) throws SQLException {
return super.getJdbcTemplate().queryForObject("select money from account where id = ?",
new BeanPropertyRowMapper(Account.class), id);
}
/** @事务
* 根据id更新账户的余额, 将异常显示抛出 */
@Override
public int updateMoney(Integer id, Float money) throws SQLException {
return super.getJdbcTemplate().update("update account set money = ? where id = ?",
money, id);
}
}
5). service业务层
public interface AccountService {
/** 转账业务 */
public boolean transfer(Integer fromId, Integer toId, Float money) throws Exception;
}
package com.itheima.service.impl;
import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
/** @事务
* 转账业务 使用注解进行声明式事务处理,使用
* @Transactional 注解,并在其中配置参数*/
@Override
@Transactional(propagation = Propagation.SUPPORTS, readOnly = false)
public boolean transfer(Integer fromId, Integer toId, Float money) throws Exception {
// 1. 查询原账户余额
Account fromMoney = accountDao.queryMoney(fromId);
if (fromMoney.getMoney() < money) {
throw new RuntimeException("账户余额不足,无法完成转账");
}
// 2. 查询被转入账户的余额
Account toMoney = accountDao.queryMoney(toId);
// 3. 扣除原账户的money
accountDao.updateMoney(fromId, fromMoney.getMoney() - money);
// 显示抛出一个异常。
//int a = 8 / 0;
// 4. 添加被转入账户的余额
accountDao.updateMoney(toId, toMoney.getMoney() + money);
return true;
}
}
6). Junit4测试代码
import config.SpringConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class MyTest {
@Autowired
private ApplicationContext ac;
/** 转账测试 */
@Test
public void testTransfer() throws Exception {
AccountService service = (AccountService)ac.getBean("accountService");
boolean res = service.transfer(4, 2, 1000F);
System.out.println(res);
}
}
7). maven工程坐标
mysql
mysql-connector-java
5.1.41
org.springframework
spring-beans
5.0.3.RELEASE
org.springframework
spring-context
5.0.3.RELEASE
org.springframework
spring-core
5.0.3.RELEASE
org.springframework
spring-expression
5.0.3.RELEASE
org.springframework
spring-aop
5.0.3.RELEASE
org.springframework
spring-test
5.0.2.RELEASE
junit
junit
4.12
test
org.aspectj
aspectjweaver
1.8.7
org.springframework
spring-jdbc
5.0.2.RELEASE