Spring第三天
AOP简介
什么是AOP?
AOP(全称:Aspect Oriented Programming)即面向切面编程,它是面向对象编程OOP的延续,与IOC并称Spring的两大核心。在Spring中的主要用于对业务逻辑的各个部分进行隔离,从而使得业务逻辑各个部分之间的耦合度降低,提高程序的可重用性,大大的提高了开发的效率。
AOP的作用以及优势
作用
在程序运行期间,在不修改源码的情况下对已有的方法进行增强,也就是使用动态代理的方式。
优势
- 减少重复代码
- 提高开发效率
- 维护方便
引入学习案例----给业务层添加事务的支持
业务层代码
package com.gzgs.service.impl;
import com.gzgs.dao.AccountDao;
import com.gzgs.domain.Account;
import com.gzgs.service.AccountService;
import java.util.List;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAll() {
return accountDao.findAll();
}
public Account findAccountById(int id) {
return accountDao.findAccountById(id);
}
public void insertAccount(Account account) {
accountDao.insertAccount(account);
}
public void deleteAccount(int id) {
accountDao.deleteAccount(id);
}
public void updateAccount(int id, Account account) {
accountDao.updateAccount(id,account);
}
public void transfer(String sourceName, String targetName, double money) {
//查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//查询转入账户
Account target=accountDao.findAccountByName(targetName);
//转出账户扣钱
source.setMoney(source.getMoney()-money);
//转入账户加钱
target.setMoney(target.getMoney()+money);
//更新转出账户
accountDao.updateAccount(source.getId(),source);
//更新转入账户
accountDao.updateAccount(target.getId(),target);
}
}
代理对象工厂代码
package com.gzgs.factory;
import com.gzgs.service.AccountService;
import com.gzgs.utils.TransactionManager;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 用于创建Service的代理对象工厂
*/
public class BeanFactory {
private AccountService accountService;
private TransactionManager txManager;
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
public AccountService getAccountService(){
return (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object rtValue=null;
try {
//开启事务
txManager.beginTransaction();
//执行操作
rtValue = method.invoke(accountService, args);
//提交事务
txManager.commit();
//返回结果
return rtValue;
}catch (Exception e){
txManager.rollback();
throw new RuntimeException(e);
}finally {
//释放连接
txManager.release();
}
}
});
}
}
AOP的相关术语
Joinpoint(连接点)
所谓连接点是指那些被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的
连接点,对应上边的例子就是AccountServiceImpl中所有的方法都是。
Pointcut(切入点)
所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义,也就是我们需要对其增强的方法。从概念上可以得知,所有的切入点都是连接点,而连接点不一定都是切入点。
Advice(通知/增强)
所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。
通知的类型: 前置通知,后置通知,异常通知,最终通知,环绕通知,根据相对与切入点的位置而定。
Introduction(引介)
引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方
法或 Field。
Target(目标对象)
代理的目标对象,也就是上面例子中的AccountServiceImpl.
Weaving(织入)
是指把增强应用到目标对象来创建新的代理对象的过程。
spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。
Proxy(代理)
一个类被 AOP 织入增强后,就产生一个结果代理类,也就是上面例子中getAccountService的返回结果。
Aspect(切面)
是切入点和通知(引介)的结合
学习 spring 中的 AOP 要明确的事
开发阶段(我们做的)
编写核心业务代码(开发主线):大部分程序员来做,要求熟悉业务需求。
把公用代码抽取出来,制作成通知。(开发阶段最后再做): AOP 编程人员来做。
在配置文件中,声明切入点与通知间的关系,即切面。: AOP 编程人员来做。
运行阶段( Spring 框架完成的)
Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。
在 spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。
基于 XML 的 AOP 配置(改善上面事务控制转账案例)
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"
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">
<!--配置AccountService-->
<bean id="accountService" class="com.gzgs.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置AccountDaoImpl对象-->
<bean id="accountDao" class="com.gzgs.dao.impl.AccountDaoImpl">
<property name="runner" ref="runner"></property>
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<!--配置QuueryRunner对象-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</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/test02"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置Connection的工具类 ConnectionUtils -->
<bean id="connectionUtils" class="com.gzgs.utils.ConnectionUtils">
<!-- 注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器-->
<bean id="txManager" class="com.gzgs.utils.TransactionManager">
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<!--配置AOP-->
<aop:config>
<!-- 配置切入点表达式 id属性用于指定表达式的唯一标识。expression属性用于指定表达式内容
此标签写在aop:aspect标签内部只能当前切面使用。
它还可以写在aop:aspect外面,此时就变成了所有切面可用
-->
<aop:pointcut id="pt1" expression="execution(* com.gzgs.service.impl.*.*(..))"></aop:pointcut>
<!--配置切面-->
<aop:aspect id="advice" ref="txManager">
<!--配置前置通知-->
<aop:before method="beginTransaction" pointcut-ref="pt1"></aop:before>
<!--配置后置置通知-->
<aop:after-returning method="commit" pointcut-ref="pt1"></aop:after-returning>
<!--配置异常通知-->
<aop:after-throwing method="rollback" pointcut-ref="pt1"></aop:after-throwing>
<!--配置最终通知-->
<aop:after method="release" pointcut-ref="pt1"></aop:after>
</aop:aspect>
</aop:config>
</beans>
基于注解 的 AOP 配置(改善上面事务控制转账案例)
在使用基于注解的AOP配置的时候,经常会出现一个后置通知执行异常的bug,这是由于四个通知的调用顺序不和逻辑所导致的,调用顺序依次是:前置通知,最终通知,后置通知。这样就会导致由于资源被释放掉于是导致后置通知执行失败,通常它的报错信息是当connection自动提交没有设置为false,这是因为它和前置通知已经不是同一个连接了。所以在使用基于注解的AOP配置的时候,最好是使用环绕通知来控制程序的执行顺序。
核心AOP代码
package com.gzgs.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
*/
@Component("transactionManager")
@Aspect
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
@Pointcut("execution(* com.gzgs.service.impl.*.*(..))")
private void pt1(){}
/**
* 开启事务
*/
public void beginTransaction(){
try {
System.out.println("我是前置");
connectionUtils.getThreadConnection().setAutoCommit(false);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback(){
try {
System.out.println("我是异常置");
connectionUtils.getThreadConnection().rollback();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 释放连接
*/
public void release(){
try {
System.out.println("释放");
connectionUtils.getThreadConnection().close();//还回连接池中
connectionUtils.removeConnection();
}catch (Exception e){
e.printStackTrace();
}
}
@Around("pt1()")
public Object aroundAdvice(ProceedingJoinPoint pjp){
Object rtValue = null;
try {
//1.获取参数
Object[] args = pjp.getArgs();
//2.开启事务
this.beginTransaction();
//3.执行方法
rtValue = pjp.proceed(args);
//4.提交事务
this.commit();
System.out.println("我是后置");
//返回结果
return rtValue;
}catch (Throwable e){
//5.回滚事务
this.rollback();
throw new RuntimeException(e);
}finally {
//6.释放资源
this.release();
}
}
}
本博客纯属个人学习笔记,学习资源来自黑马训练营,如有错误,感激指正