文章目录
1.引入AOP
1.1案例中存在的问题
- 先看业务层实现类的代码:
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao; }
@Override
public void saveAccount(Account account) throws SQLException {
accountDao.save(account);
}
@Override
public void updateAccount(Account account) throws SQLException{
accountDao.update(account);
}
@Override
public void deleteAccount(Integer accountId) throws SQLException{
accountDao.delete(accountId);
}
@Override
public Account findAccountById(Integer accountId) throws SQLException {
return accountDao.findById(accountId);
}
@Override
public List<Account> findAllAccount() throws SQLException{
return accountDao.findAll();
}
}
- 在涉及到对数据库的操作问题时,我们要想到事务的控制,在
上面的代码中事务是被自动控制了
,即我们使用了connection 对象的 setAutoCommit(true)
。- 因为上述代码每次都只执行了一条sql语句,所以这样完全没有问题,但是如果出现多条sql语句的情况,就会出现问题。
- 我们在业务层中添加一个新的方法:
public void transfer(String sourceName, String targetName, Float money) {
//2.1根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName); //获取一个连接
//2.2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName); //获取一个连接
//2.3转出减钱
source.setMoney(source.getMoney()-money);
//2.4转入加钱
target.setMoney(target.getMoney()+money);
//2.5更新转入账户
accountDao.updateAccount(source); //获取一个连接
int i = 1/0; //问题:事务并不是一致的
//2.6更新转出账户
accountDao.updateAccount(target); //获取一个连接
}
- 在上面的转账案例中,我们故意设置了一个错误,这样明显会导致转账的异常,即转入的账户正常转入,而转出的账户出现异常。
- 出现上述错误的原因就
是事务的不一致造成的
。每次执行持久层的方法都是独立事务,它们各自互不影响,无法实现事务的控制。
1.2问题的解决
- 解决办法:
让业务层来控制事务的提交和回滚。
- 要想实现事务的控制,我们需要持久层中
实际操作数据库的连接都是同一个连接。
也就说要成功一起成功,失败一起失败从而实现事务的控制。 - 要想让所有操作数据库的Connection都是同一个Connection,我们需要借助于
ThreadLocal对象把Connection和当前的线程进行绑定
,从而使一个线程只能有一个控制事务的对象。
/**
* 连接的工具类
* 作用:用于从数据源(datasource)中获取一个连接,并且实现和线程的绑定
*/
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* 获取当前线程的连接
* @return
*/
public Connection getThreadConnection(){
try{
//1.先从ThreadLocal上获取
Connection con = tl.get();
if (con == null){
//当前线程无连接,此时从数据源中获取一个连接,并和当前线程绑定
con = dataSource.getConnection();
tl.set(con);
}
//返回当前线程的连接
return con;
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
* 把连接和线程解绑
*/
public void removeConnection(){
tl.remove();
}
}
- 在完成线程的绑定后,就可以来写事务控制的代码,这里我们写一个和事务控制相关的工具类
TransactionManager
,帮助我们更好的实现事务的控制。
/**
* 和事务相关的工具类,它包含了开启事务,提交事务,回滚事务和释放连接
*/
public class TransactionManager {
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 释放连接
*/
public void release(){
try {
/**
* 这里的释放的真正含义是把连接还回了连接池中,而不是真正的close
* 同时,线程也同理,线程被还到线程池中,但是线程和连接还处于绑定状态,下一次再获取连接时
* 能够获取到,但不能使用了,所以这里要有一个解绑的操作
*/
connectionUtils.getThreadConnection().close();
connectionUtils.removeConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
- 在业务层中加上控制事务的代码:
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
private TransactionManager txManager;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
@Override
public void transfer(String sourceName, String targetName, Double money) {
try {
// 1. 开启事务
txManager.beginTransaction();
// 2. 执行操作
// 2.1 获取转出账户和转入账户
Account source = accountDao.getAccountByName(sourceName);
Account target = accountDao.getAccountByName(targetName);
// 2.2 转账
source.setBalance(source.getBalance() - money);
target.setBalance(target.getBalance() + money);
// 2.3 更新账户
accountDao.updateAccount(source);
// 模拟异常
int i = 1 / 0;
accountDao.updateAccount(target);
// 3. 提交事务
txManager.commit();
} catch (Exception e) {
// 5. 回滚操作
txManager.rollback();
throw new RuntimeException(e);
} finally {
// 6. 释放连接
txManager.release();
}
}
}
1.3新的问题及解决(动态代理)
-
观察上一小节中业务层的代码,发现加上事务控制的代码后,有下面这两个问题:
- 1.显得业务层的方法特别的臃肿,如果业务层中有很多个方法,那么每个方法都要加上事务控制的代码,
整个业务层有许多重复的代码。
- 2.如果其中某一个控制事务的方法名发生了变更,那么整个业务层会有许多要修改的地方。
- 1.显得业务层的方法特别的臃肿,如果业务层中有很多个方法,那么每个方法都要加上事务控制的代码,
-
那么问题要如何解决呢?这里我们使用动态代理的方式,
把事务的控制交给代理的对象。
/**
* 用于创建Service代理对象的bean
*/
public class BeanFactory {
private IAccountService accountService;
private TransactionManager transactionManager;
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public final void setAccountService(IAccountService accountService) {
this.accountService = accountService;
}
/**
* 获取Service代理对象
* @return
*/
public IAccountService getAccountService() {
return (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
accountService.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("transfer........");
Object rtvalue = null;
try {
//1.开启事务
transactionManager.beginTransaction();
//2.执行操作
rtvalue = method.invoke(accountService,args);
//3.提交事务
transactionManager.commit();
}catch (Exception e){
//回滚操作
transactionManager.rollback();
}finally {
transactionManager.release();
}
return rtvalue;
}
});
}
}
到这里我们可以把前面业务层控制事务的代码全部去掉了,在业务层中只专注于业务代码的编写。
配置文件bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountService" class="com.zut.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<bean id="accountDao" class="com.zut.dao.impl.AccountDaoImpl">
<property name="runner" ref="queryRunner"></property>
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<!--配置QueryRunner-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"></bean>
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/student"></property>
<property name="user" value="root"></property>
<property name="password" value="ljt074517"></property>
</bean>
<!--配置Connection的工具类-->
<bean id="connectionUtils" class="com.zut.utils.ConnectionUtils">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置管理事务的工具类-->
<bean id="transactionManager" class="com.zut.utils.TransactionManager">
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<!--BeanFactory-->
<bean id="beanfactory" class="com.zut.factory.BeanFactory">
<property name="accountService" ref="accountService"></property>
<property name="transactionManager" ref="transactionManager"></property>
</bean>
<!--配置代理的service-->
<bean id="proxyAccountService" factory-bean="beanfactory" factory-method="getAccountService"></bean>
</beans>
2.AOP
- 前面的章节说了那么多实际上只是为了引入AOP,那么到底什么是AOP呢?事实上
spring的AOP就是通过配置的方式,实现前面事务控制的功能。
2.1AOP的概念
- AOP:
- AOP为Aspect Oriented Programming的缩写,意为:
面向切面编程
,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。 - 简单来说就是使用动态代理,
在不修改源码的基础上,对已有的方法进行增强。
- AOP为Aspect Oriented Programming的缩写,意为:
- 优势:
- 减少重复代码
- 提高开发效率
- 维护方便
2.2AOP的相关术语
-
Joinpoint(连接点) :
- 被拦截到的方法(上面例子中业务层的方法都是连接点)
-
Pointcut(切入点):
- 被增强的方法
-
Advice(通知/增强):
- 所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。
- 通知的类型:
前置通知、后置通知、异常通知、最终通知、环绕通知。
-
Introduction(引介):
- 引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方法或 Field。
-
Target(目标对象):
- 代理的目标对象。
-
Weaving(织入):
- 是指把增强应用到目标对象来创建新的代理对象的过程。
-
Proxy(代理):
- 一个类被 AOP 织入增强后,就产生一个结果代理类。
-
Aspect(切面):
是切入点和通知(引介)的结合。
3.Spring基于XML的AOP配置
3.1使用XML配置AOP的步骤
- 以之前CRUD案例为基础,不过不在自己创建代理工厂来实现事务控制,而是使用AOP来实现事务的控制。
- 首先需要在pom.xml引入以下坐标 ,以能够正常使用AOP
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
- 在配置文件
bean.xml
中引入约束,并将通知类注入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"
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.xsd">
<!--配置Logger通知类-->
<bean id="logger" class="com.zut.utils.Logger"></bean>
- 使用
<aop:config>
标签开始声明 AOP 配置,所有关于AOP配置的代码都写在<aop:config>
标签内
<aop:config>
<!-- AOP配置的代码都写在此处 -->
</aop:config>
- 使用
<aop:aspect>
标签配置切面,其属性如下id:
是给切面提供一个唯一表示ref:
是指定通知类bean的Id
<aop:config>
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知的类型要写在此处-->
</aop:aspect>
</aop:config>
- 使用
<aop:pointcut>
标签配置切入点表达式,其属性如下:id
: 指定切入点表达式的idexpression
: 指定切入点表达式
<aop:config>
<aop:pointcut id="pt1" expression="execution(* com.zut.service.impl.*.*(..))"/>
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知的类型要写在此处-->
</aop:aspect>
</aop:config>
- 在
<aop:aspect>标签的内部
使用对应标签来配置通知的类型<aop:before>
:表示前置通知method
:指定那个方法是前置通知pointcut属性
:用于指定切面表达式,该表达式的含义指的是对业务层中哪些方法增强pointcut-ref 属性
:指定切入点表达式的引用
<aop:after-returning>
标签用于配置后置通知,指定增强的方法在切入点方法正常运行之后执行,与异常通知是互斥的,属性同上<aop:afterthrowing>
标签用于配置异常通知,指定增强的方法在切入点方法产生异常之后执行,与后置通知是互斥的,属性同上<aop:after>
标签用于配置最终通知,指定增强的方法无论切入点方法是否产生异常都会执行,属性同上<aop:arround>
标签用于配置环绕通知,属性同上
<aop:config>
<aop:pointcut id="pt1" expression="execution(* com.zut.service.impl.*.*(..))"/>
<aop:aspect id="logAdvice" ref="logger">
<aop:before method="beforeprintLog" pointcut-ref="pt1"></aop:before>
<aop:after-returning method="afterRunningPrintlog" pointcut-ref="pt1"></aop:after-returning>
<aop:after-throwing method="afterThrowingPrintlog" pointcut-ref="pt1"></aop:after-throwing>
<aop:after method="afterPrintlog" pointcut-ref="pt1"></aop:after>
<!--环绕通知一般单独使用-->
<!-- <aop:around method="printLogAround" pointcut-ref="pt1"></aop:around> -->
</aop:aspect>
</aop:config>
3.2切入点表达式
-
切入点表达式的写法:
execution([修饰符] 返回值类型 包路径.类名.方法名(参数))
-
标准的切入点表达式写法:
public void com.zut.service.impl.AccountServiceImpl.savaAccount(com.zut.domain.Account)
-
访问修饰符可以省略
void com.zut.service.impl.AccountServiceImpl.savaAccount(com.zut.domain.Account)
-
返回值可以使用通配符,表示任意返回值
* com.zut.service.impl.AccountServiceImpl.savaAccount(com.zut.domain.Account)
-
包名可以使用通配符,表示任意包。但是有几级包,就需要写几个
*
* *.*.*.*.AccountServiceImpl.savaAccount(com.zut.domain.Account)
-
包名可以使用
..
表示当前包及其子包* *..AccountServiceImpl.savaAccount(com.zut.domain.Account)
* com..AccountServiceImpl.savaAccount(com.zut.domain.Account)
-
类名和方法名都可以使用*来实现通配
* com..*.*(com.zut.domain.Account)
-
参数列表可以直接写数据类型,也可以用通配符
*
来表示任意类型,但是必须有参数* com..*.*(*)
-
参数列表可以使用
..
表示有无参数均可,有参数可以是任意类型* com..*.*(..)
-
全通配写法
* *..*.*(..)
-
实际开发中切入点表达式的通常写法(切到业务层实现类下的所有方法)
* com.zut.service.impl.*.*(..)
3.3环绕通知
-
它是 spring 框架为我们提供的一种可以在代码中手动控制增强代码什么时候执行的方式,它一般情况下是单独使用的
-
Spring框架为我们提供一个接口
ProceedingJoinPoint
,它的实例对象可以作为环绕通知方法的参数,通过参数控制被增强方法的执行时机.ProceedingJoinPoint
对象的getArgs()方法返回被拦截的参数ProceedingJoinPoint
对象的proceed()方法执行被拦截的方法
-
通知类中环绕通知的具体实现:
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtValue = null;
try {
Object[] args = pjp.getArgs(); //得到方法执行所需参数
System.out.println("环绕通知Logger类的aroundPrintLog方法开始记录日志了。。前置");
rtValue = pjp.proceed(args); //明确调用切入点方法
System.out.println("环绕通知Logger类的aroundPrintLog方法开始记录日志了。。后置");
return rtValue;
}catch (Throwable t){
System.out.println("环绕通知Logger类的aroundPrintLog方法开始记录日志了。。异常");
throw new RuntimeException(t);
}finally {
System.out.println("环绕通知Logger类的aroundPrintLog方法开始记录日志了。。最终");
}
}
4.Spring中基于注解AOP配置
4.1XML+注解的方式
- 首先在bean.xml配置文件中开启对注解AOP的支持
<!--配置Spring开启注解Aop的支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
- 用于声明切面的注解:
@Aspect
: 声明当前类为通知类,该类定义了一个切面.相当于xml配置中的<aop:aspect>
标签
@Component("logger")
@Aspect //表示当前类是一个切面类
public class Logger {
// .......
- 用于声明通知的注解:
@Before
: 声明该方法为前置通知。相当于xml配置中的<aop:before>
标签@AfterReturning
: 声明该方法为后置通知.相当于xml配置中的<aop:after-returning>
标签@AfterThrowing
: 声明该方法为异常通知.相当于xml配置中的<aop:after-throwing>
标签@After
: 声明该方法为最终通知.相当于xml配置中的<aop:after>
标签@Around
: 声明该方法为环绕通知.相当于xml配置中的<aop:around>
标签- 属性:
value
: 用于指定切入点表达式或切入点表达式的引用
@Component("logger")
@Aspect //表示当前类是一个切面类
public class Logger {
@Before("execution(* com.zut.service.impl.*.*(..))")
public void beforeprintLog(){
System.out.println("前置通知Logger类的beforeprintLog方法开始记录日志了");
}
@AfterReturning("execution(* com.zut.service.impl.*.*(..))")
public void afterRunningPrintlog(){
System.out.println("后置通知Logger类的afterRunningPrintlog方法开始记录日志了");
}
@AfterThrowing("execution(* com.zut.service.impl.*.*(..))")
public void afterThrowingPrintlog(){
System.out.println("异常通知Logger类的afterThrowingPrintlog方法开始记录日志了");
}
@After("execution(* com.zut.service.impl.*.*(..))")
public void afterPrintlog(){
System.out.println("最终通知Logger类的afterPrintlog方法开始记录日志了");
}
}
- 用于指定切入点表达式的注解:
@Pointcut
: 指定切入点表达式,其属性如下:- value: 指定表达式的内容
@Pointcut
注解没有id属性,通过调用被注解的方法获取切入点表达式.
@Component("logger")
@Aspect //表示当前类是一个切面类
public class Logger {
@Pointcut("execution(* com.zut.service.impl.*.*(..))")
private void pt1(){}
/**
* 前置通知
* 计划在切入点方法之前执行(切入点方法就是业务层方法)
*/
@Before("pt1()")
public void beforeprintLog(){
System.out.println("前置通知Logger类的beforeprintLog方法开始记录日志了");
}
/**
*后置通知
*/
@AfterReturning("pt1()")
public void afterRunningPrintlog(){
System.out.println("后置通知Logger类的afterRunningPrintlog方法开始记录日志了");
}
/**
* 异常通知
*/
@AfterThrowing("pt1()")
public void afterThrowingPrintlog(){
System.out.println("异常通知Logger类的afterThrowingPrintlog方法开始记录日志了");
}
/**
* 最终通知
*/
@After("pt1()")
public void afterPrintlog(){
System.out.println("最终通知Logger类的afterPrintlog方法开始记录日志了");
}
}
4.2纯注解配置AOP
- 在Spring配置类前添加
@EnableAspectJAutoProxy
注解,可以使用纯注解方式配置AOP。
@Configuration
@ComponentScan("com.zut")
@EnableAspectJAutoProxy// 开启aop支持
public class SpringConfiguration {
}
4.3使用注解AOP存在的问题
-
当使用注解来配置前置通知、后置通知、异常通知以及环绕通知时,由于 Spring 的 bug,导致了通知被调用的顺序有误,如图:
-
使用注解配置AOP后,四个通知的调用顺序依次是:前置通知,最终通知,后置通知. 这会导致一些资源在执行最终通知时提前被释放掉了,而执行后置通知时就会出错。
-
要解决这个问题
只要使用环绕通知即可
,因为环绕通知的调用顺序与spring无关,是由我们自己决定的。