SpringMVC学习记录文章目录:
1、程序的耦合和解耦思路
2、使用springIOC解决程序耦合的前期准备
3、BeanFactory和ApplicationContext的区别及ApplicationContext接口的实现类
4、bean标签及其实例化的3种方式
5、bean的作用范围和生命周期
6、Spring的依赖注入
7、基于注解的IOC环境搭建
8、基于注解的IOC-常用注解(Spring2.5规范)
9、Spring常用注解-新(Spring2.5规范以上)
10、Spring整合Junit单元测试
11、AOP的相关概念
12、Spring中AOP的术语
13、SpringAOP常用标签解释说明
14、SpringAOP中切入点表达式说明
15、SpringAOP类型说明及环绕通知的特殊说明
16、基于xml的SpringAOP配置
17、SpringAOP常用注解
18、基于注解的SpringAOP配置
19、Spring中的JdbcTemplate
20、Spring中的事务控制
1.Spring事务控制我们要明确的
第一:
- JavaEE体系进行分层开发,事务处理位于业务层,Spring提供了分层设计业务层的事务处理解决方案。
第二:
- spring框架提供了一组事务控制的接口。这组接口是在spring-tx-4.2.4.RELEASE.jar中。
第三:
- spring的事务控制都是基于AOP的,它既可以使用编程的方式实现,也可以使用配置的方式实现。学习的重点是使用配置的方式实现。
2.Spring中事务控制的API介绍
2.1 PlatformTransactionManager
此接口是spring的事务管理器,它里面提供了我们常用的操作事务的方法,如下
PlatformTransactionManager接口提供事务操作的方法,包括有三个具体操作:
- 获取事物状态信息
- TransactionStatus getTransaction(TransactionDefinition definition)
- 提交事物
- void commit(TransactionStatus status)
- 回滚事务
- void rollback(TransactionStatus status)
我们在开发中都是使用它的实现类,如下
DataSourceTransactionManager
- 使用SpringJDBC或MyBatis进行持久化数据使用时
HibernateTransactionManager
- 使用Hibernate3.0版本进行持久化数据时使用
JpaTransactionManager
- 使用Jpa进行持久化数据时使用
JdoTransactionManager
- 当持久化机制是Jdo时使用
JtaTrasactionManager
- 使用JTA实现管理事务,在一个事务跨越多个资源时必须使用
真正管理事务的对象
- org.springframework.jdbc.datasource.DataSourceTransactionManager 使用Spring JDBC或iBatis 进行持久化数据时使用
- org.springframework.orm.hibernate3.HibernateTransactionManager 使用Hibernate版本进行持久化数据时使用
2.2 TransactionDefinition
它是事务的定义信息对象,里面有如下方法:
获取事务对象名称
- String getName();
获取事务隔离级
- int getIsolationLevel();
获取事务传播行为
- int getPropagationBehavior();
获取事务超时时间
- int getTimeout();
获取事务是否只读
- boolean isReadOnly();
2.2.1 事务的隔离级别
事务的隔离级反映事务提交并发访问时的处理态度
- ISOLATION_DEFAULT
- 默认级别,归属下列某一种
- ISOLATION_READ_UNCOMMITTED
- 可以读取未提交的数据
- ISOLATION_READ_COMMITTED
- 只能读取已提交数据,解决数据脏读问题 (Oracle默认级别)
- ISOLATION_REPEATABLE_READ
- 是否读取其他事务提交修改后的数据,解决不可重复读问题(MySQL默认级别)
- ISOLATION_SERIALIZABLE
- 是否读取其他事务提交添加后的数据,解决幻影问题
2.2.2 事务的传播行为
- REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
- SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
- MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
- REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
- NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
- NEVER:以非事务方式运行,如果当前存在事务,抛出异常
- NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行REQUIRED类似的操作。
2.2.3 超时时间
默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
2.2.4 是否是只读事务
建议查询时设置为只读。
2.3 TransactionStatus
此接口提供的是事务具体的运行状态,方法介绍如下:
TransactionStatus接口描述了某个时间点上的事务对象的状态信息,包含六种操作:
- 刷新事务
- void flush();
- 获取是否存在存储点
- boolean hasSavepoint();
- 获取事务是否完成
- boolean isCompleted();
- 获取事务是否为新事务
- boolean isNewTransaction();
- 获取事务是否回滚
- boolean isRollbackOnly();
- 设置事务回滚
- void setRollbackOnly();
3.基于XML的声明式事务控制(配置方式)重点
3.1 环境搭建
3.1.1 第一步:拷贝必要的jar包到工程的lib目录
3.1.2 第二步:创建spring的配置文件并导入约束
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
3.1.3 第三步:准备数据库表和实体类
创建数据库:
create database spring_day04;
use spring_day04;
创建表:
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
/**
* 账户的实体
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
}
}
3.1.4 第四步:编写业务层接口和实现类
/**
* 账户的业务层接口
*/
public interface IAccountService {
/**
* 根据id查询账户信息
* @param id
* @return
*/
Account findAccountById(Integer id);//查
/**
* 转账
* @param sourceName 转出账户名称
* @param targeName 转入账户名称
* @param money 转账金额
*/
void transfer(String sourceName,String targeName,Float money);//增删改
}
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
public void transfer(String sourceName, String targeName, Float money) {
//1.根据名称查询两个账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName);
//2.修改两个账户的金额
source.setMoney(source.getMoney()-money);//转出账户减钱
target.setMoney(target.getMoney()+money);//转入账户加钱
//3.更新两个账户
accountDao.updateAccount(source);
int i=1/0;
accountDao.updateAccount(target);
}
}
3.1.5 第五步:编写Dao接口和实现类
/**
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* 根据id查询账户信息
* @param id
* @return
*/
Account findAccountById(Integer id);
/**
* 根据名称查询账户信息
* @return
*/
Account findAccountByName(String name);
/**
* 更新账户信息
* @param account
*/
void updateAccount(Account account);
}
/**
* 账户的持久层实现类
* 此版本dao,只需要给它的父类注入一个数据源
*/
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer id) {
List<Account> list = getJdbcTemplate().query("select * from account where id = ? ",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> list = getJdbcTemplate().query("select * from account where name = ? ",new AccountRowMapper(),name);
if(list.isEmpty()){
return null;
}
if(list.size()>1){
throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
}
return list.get(0);
}
@Override
public void updateAccount(Account account) {
getJdbcTemplate().update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
}
}
/**
* 账户的封装类RowMapper的实现类
*/
public class AccountRowMapper implements RowMapper<Account>{
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getFloat("money"));
return account;
}
}
3.1.6 第六步:在配置文件中配置业务层和持久层对
<!-- 配置service -->
<bean id="accountService" class="com.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置dao -->
<bean id="accountDao" class="com.dao.impl.AccountDaoImpl">
<!-- 注入dataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///day_spring04"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
3.2 配置步骤
3.2.1 第一步:配置事务管理器
<!-- 配置一个事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入DataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
3.2.2 第二步:配置事务的通知引用事务管理器
<!-- 事务的配置 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
</tx:advice>
3.2.3 第三步:配置事务的属性
<!--在tx:advice标签内部 配置事务的属性 -->
<tx:attributes>
<!-- 指定方法名称:是业务核心方法
read-only:是否是只读事务。默认false,不只读。
isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
propagation:指定事务的传播行为。
timeout:指定超时时间。默认值为:-1。永不超时。
rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。没有默认值,任何异常都回滚。
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,任何异常都回滚。
-->
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>
3.2.4 第四步:配置AOP-切入点表达式
<!-- 配置aop -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut expression="execution(* com.service.impl.*.*(..))" id="pt1"/>
</aop:config>
3.2.5 第五步:配置切入点表达式和事务通知的对应关系
<!-- 在aop:config标签内部:建立事务的通知和切入点表达式的关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
4.基于XML和注解组合使用的整合方式
4.1 环境搭建
4.1.1 第一步:拷贝必备的jar包到工程的lib目录
在这里插入图片描述
4.1.2 第二步:创建spring的配置文件导入约束并配置扫描的包
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring要扫描的包 -->
<context:component-scan base-package="com"></context:component-scan>
</beans>
4.1.3 第三步:创建数据库表和实体类
和基于xml的配置相同,略。
4.1.4 第四步:创建业务层接口和实现类并使用注解让spring管理
业务层接口和基于xml配置的时候相同
/**
* 账户的业务层实现类
*/
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
public void transfer(String sourceName, String targeName, Float money) {
//1.根据名称查询两个账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName);
//2.修改两个账户的金额
source.setMoney(source.getMoney()-money);//转出账户减钱
target.setMoney(target.getMoney()+money);//转入账户加钱
//3.更新两个账户
accountDao.updateAccount(source);
int i=1/0;
accountDao.updateAccount(target);
}
}
4.1.5 第五步:创建Dao接口和实现类并使用注解让spring管理
Dao层接口和AccountRowMapper与基于xml配置的时候相同
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Account findAccountById(Integer id) {
List<Account> list = jdbcTemplate.query("select * from account where id = ? ",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> list = jdbcTemplate.query("select * from account where name = ? ",new AccountRowMapper(),name);
if(list.isEmpty()){
return null;
}
if(list.size()>1){
throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
}
return list.get(0);
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
}
}
4.2 配置步骤
4.2.1 第一步:配置数据源和JdbcTemplate
<!-- 配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///day_spring04"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
4.2.2 第二步:配置事务管理器并注入数据源
<!-- 配置JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
4.2.3 第三步:在业务层使用@Transactional注解
@Service("accountService")
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public void transfer(String sourceName, String targeName, Float money) {
//1.根据名称查询两个账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName);
//2.修改两个账户的金额
source.setMoney(source.getMoney()-money);//转出账户减钱
target.setMoney(target.getMoney()+money);//转入账户加钱
//3.更新两个账户
accountDao.updateAccount(source);
//int i=1/0;
accountDao.updateAccount(target);
}
}
该注解的属性和xml中的属性含义一致。该注解可以出现在接口上,类上和方法上。
出现接口上,表示该接口的所有实现类都有事务支持。
出现在类上,表示类中所有方法有事务支持
出现在方法上,表示方法有事务支持。
以上三个位置的优先级:方法>类>接口
4.2.4 第四步:在配置文件中开启spring对注解事务的支持
<!-- 开启spring对注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
5.基于纯注解的声明式事务控制(配置方式)重点
5.1 环境搭建
5.1.1 第一步:拷贝必备的jar包到工程的lib目录
5.1.2 第二步:创建一个类用于加载spring的配置并指定要扫描的包
/**
* 用于初始化spring容器的配置类
*/
@Configuration
@ComponentScan(basePackages="com.itheima")
public class SpringConfiguration {
}
5.1.3 第三步:创建数据库表和实体类
和基于xml的配置相同,略。
5.1.4 第四步:创建业务层接口和实现类并使用注解让spring管理
业务层接口和基于xml配置的时候相同,略。
/**
* 账户的业务层实现类
*/
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
public void transfer(String sourceName, String targeName, Float money) {
//1.根据名称查询两个账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName);
//2.修改两个账户的金额
source.setMoney(source.getMoney()-money);//转出账户减钱
target.setMoney(target.getMoney()+money);//转入账户加钱
//3.更新两个账户
accountDao.updateAccount(source);
int i=1/0;
accountDao.updateAccount(target);
}
}
5.1.5 第五步:创建Dao接口和实现类并使用注解让spring管理
Dao层接口和AccountRowMapper与基于xml配置的时候相同,略。
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Account findAccountById(Integer id) {
List<Account> list = jdbcTemplate.query("select * from account where id = ? ",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> list = jdbcTemplate.query("select * from account where name = ? ",new AccountRowMapper(),name);
if(list.isEmpty()){
return null;
}
if(list.size()>1){
throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
}
return list.get(0);
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
}
}
5.2 配置步骤
5.2.1 第一步:使用@Bean注解配置数据源
@Bean(name = "dataSource")
public DataSource createDS() throws Exception {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///day_spring04");
return dataSource;
}
5.2.2 第二步:使用@Bean注解配置配置事务管理器
@Bean
public PlatformTransactionManager
createTransactionManager(@Qualifier("dataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
5.2.3 第三步:使用@Bean注解配置JdbcTemplate
@Bean
public JdbcTemplate createTemplate(@Qualifier("dataSource") DataSource dataSource)
{
return new JdbcTemplate(dataSource);
}
5.2.4 第四步:在需要控制事务的业务层实现类上使用@Transactional注解
@Service("accountService")
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public void transfer(String sourceName, String targeName, Float money) {
//1.根据名称查询两个账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName);
//2.修改两个账户的金额
source.setMoney(source.getMoney()-money);//转出账户减钱
target.setMoney(target.getMoney()+money);//转入账户加钱
//3.更新两个账户
accountDao.updateAccount(source);
//int i=1/0;
accountDao.updateAccount(target);
}
}
该注解的属性和xml中的属性含义一致。该注解可以出现在接口上,类上和方法上。
出现接口上,表示该接口的所有实现类都有事务支持。
出现在类上,表示类中所有方法有事务支持
出现在方法上,表示方法有事务支持。
以上三个位置的优先级:方法>类>接口。
5.2.5 第五步:使用@EnableTransactionManagement开启spring对注解事务的的支持
@Configuration
@EnableTransactionManagement
public class SpringTxConfiguration {
//里面配置数据源,配置JdbcTemplate,配置事务管理器。在之前的步骤已经写过了。
}