Spring AOP

Spring AOP(面向切面编程)

一、什么是AOP

AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善。OOP引入封装、继承、多态等概念来建立一种对象层次结构,用于模拟公共行为的一个集合。不过OOP允许开发者定义纵向的关系,但并不适合定义横向的关系,例如日志功能。日志代码往往横向地散布在所有对象层次中,而与它对应的对象的核心功能毫无关系对于其他类型的代码,如安全性、异常处理和透明的持续性也都是如此,这种散布在各处的无关的代码被称为横切(cross cutting),在OOP设计中,它导致了大量代码的重复,而不利于各个模块的重用。

AOP技术恰恰相反,它利用一种称为"横切"的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为"Aspect",即切面。所谓"切面",简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。

springAOP主要就是将业务中的公共代码抽取出来,做成通知,再通过配置文件配置声明切面,将公共代码在事务执行过程中按照相应的顺序执行。

二、作用

  1. 在程序运行期间,不修改源码对已有方法进行增强
  2. 减少重复代码
  3. 提高开发效率
  4. 维护方便

三、AOP相关术语

  1. Joinpoint(连接点)
    所谓连接点是指那些被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的连接点。
  2. Pointcut(切入点)
    所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义。
  3. Advice(通知/增强)
    所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。
    通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
  4. Introduction(引介)
    引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方
    法或 Field。
  5. Target(目标对象)
    代理的目标对象。
  6. Weaving(织入)
    是指把增强应用到目标对象来创建新的代理对象的过程。
    spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入
  7. Proxy(代理)
    一个类被 AOP 织入增强后,就产生一个结果代理类
  8. Aspect(切面)
    是切入点和通知(引介)的结合。

四、编写AOP例子

本例子针对顾客账户的CRUD操作

对于顾客账户转账操作(账户更新),在事务执行之前,需要进行事务开启,事务自动提交关闭(防止执行过程中出现故障,一方已成功转账,一方却因为执行过程出现异常没法收到转账,账户余额不变,导致数据的不一致,改为手动提交,执行出现异常时回滚事务),改为手动提交,事务执行成功进行事务提交操作(commit),事务执行过程出现异常时进行事务回滚操作(rollback),在事务执行完成之后进行资源的释放(release)。对于其他事务,账户保存、账户查询、账户修改等操作,在执行事务过程中同时需要在事务执行的前后进行这些操作,这样一来,代码就会显得臃肿。于是我们利用springAOP编程,将事务执行过程中需要执行的公共代码抽取出来,通过配置,将公共代码在执行事务过程中按相应的执行顺序进行执行。

未使用AOP前的账户操作代码

Account的service类

public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao = new AccountDaoImpl();
    @Override
    public void saveAccount(Account account) {
        try {
            TransactionManager.beginTransaction();
            accountDao.save(account);
            TransactionManager.commit();
        } catch (Exception e) {
            TransactionManager.rollback();
            e.printStackTrace();
        }finally {
            TransactionManager.release();
        } }
    @Override
    public void updateAccount(Account account) {
        try {
            TransactionManager.beginTransaction();
            accountDao.update(account);
            TransactionManager.commit();
        } catch (Exception e) {
            TransactionManager.rollback();
            e.printStackTrace();
        }finally {
            TransactionManager.release();
        } }
    @Override
    public void deleteAccount(Integer accountId) {
        try {
            TransactionManager.beginTransaction();
            accountDao.delete(accountId);
            TransactionManager.commit();
        } catch (Exception e) {
            TransactionManager.rollback();
            e.printStackTrace();
        }finally {
            TransactionManager.release();
        } }
    @Override
    public Account findAccountById(Integer accountId) {
        Account account = null;
        try {
            TransactionManager.beginTransaction();
            account = accountDao.findById(accountId);
            TransactionManager.commit();
            return account;
        } catch (Exception e) {
            TransactionManager.rollback();
            e.printStackTrace();
        }finally {
            TransactionManager.release();
        }
        return null; }
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        try {
            TransactionManager.beginTransaction();
            Account source = accountDao.findByName(sourceName);
            Account target = accountDao.findByName(targetName);
            source.setMoney(source.getMoney()-money);
            target.setMoney(target.getMoney()+money);
            accountDao.update(source);
            //int i=1/0;
            accountDao.update(target);
            TransactionManager.commit();
        } catch (Exception e) {
            TransactionManager.rollback();
            e.printStackTrace();
        }finally {
            TransactionManager.release();
        }
    }
}

TransactionManager 类的代码:

/**
 * 事务相关工具类
 * 提交,开启,回滚事务,释放连接等
 */
public class TransactionManager {

    private ConnectionUtils connectionUtils;
    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }
    /**
     * 开启事务
     */
    public void beginTransaction(){
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
            System.out.println("开启了事务");

        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 提交事务
     */
    public void commit(){
        try {
            connectionUtils.getThreadConnection().commit();
            System.out.println("提交了事务");
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 回滚事务
     */
    public void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
            System.out.println("回滚了事务");
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 释放事务
     */
    public void release(){
        try {
            connectionUtils.getThreadConnection().close();
            connectionUtils.removeConnection();
            System.out.println("释放了事务");
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

这样一来,业务层方法变得臃肿了,里面充斥着很多重复代码。并且业务层方法和事务控制方法耦合了。如果我们此时提交,回滚,释放资源中任何一个方法名变更,都需要修改业务层的代码,况且这还只是一个业务层实现类,而实际的项目中这种业务层实现类可能有十几个甚至几十个。

使用AOP进行配置

配置步骤

1、把通知类(TransactionManager )用 bean 标签配置起来

<!-- 配置通知类 --> 
<bean id="txManager" class="com.itheima.utils.TransactionManager"> 
	<property name="dbAssit" ref="dbAssit"></property>
</bean>

2、使用 aop:config 声明 aop 配置

<aop:config>
	<!-- 配置的代码都写在此处 -->
</aop:config>

3、使用 aop:aspect 配置切面

/**
aop:aspect:
作用:
用于配置切面。
属性:
id:给切面提供一个唯一标识。
ref:引用配置好的通知类 bean 的 id。
**/
 <aop:aspect id="txAdvice" ref="txManager">
	<!--配置通知的类型要写在此处-->
</aop:aspect>

4、使用 aop:pointcut 配置切入点表达式

/**
aop:pointcut:
作用:
用于配置切入点表达式。就是指定对哪些类的哪些方法进行增强,对于要增强的类,写上全限定类名。
属性:
expression:用于定义切入点表达式。
id:用于给切入点表达式提供一个唯一标识
*/
<aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"/>

切入点表达式说明

execution(表达式)
表达式语法:execution([修饰符] 返回值类型 包名.类名.方法名(参数))

全匹配方式(访问修饰符可以省略):

(public )void com.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)

返回值可以使用*号,表示任意返回值

void 
* com.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)

包名可以使用星号,表示任意包,但是有几级包,需要写几个*

com.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)

* *.*.*.*.AccountServiceImpl.saveAccount(com.itheima.domain.Account)

使用..来表示当前包,及其子包
* com..AccountServiceImpl.saveAccount(com.itheima.domain.Account)

类名可以使用*号,表示任意类
* com..*.saveAccount(com.itheima.domain.Account)

方法名可以使用*号,表示任意方法
* com..*.*( com.itheima.domain.Account)

参数列表可以使用*,表示参数可以是任意数据类型,但是必须有参数
* com..*.*(*)

参数列表可以使用..表示有无参数均可,有参数可以是任意类型
* com..*.*(..)

全通配方式:
* *..*.*(..)

通常情况下,我们都是对业务层的方法进行增强,所以切入点表达式都是切到业务层实现类。

execution(* com.itheima.service.impl.*.*(..))

配置完成代码如下:

<bean id="txManager" class="com.itheima.utils.TransactionManager">
        <property name="connectionUtils" ref="connectionUtils"></property>
</bean>

<aop:config>	
		//切入点表达式
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"/>
        //配置切面
        <aop:aspect id="txAdvice" ref="txManager">
        	//事务执行前执行该方法
            <aop:before method="beginTransaction" pointcut-ref="pt1"></aop:before>
            //事务执行成功后执行该方法
            <aop:after-returning method="commit" pointcut-ref="pt1"></aop:after-returning>
           	//事务执行过程中出现异常执行该方法(与前面commit互斥,二者只能有一个执行)
            <aop:after-throwing method="rollback" pointcut-ref="pt1"></aop:after-throwing>
            //最后执行的方法
            <aop:after method="release" pointcut-ref="pt1"></aop:after>
        </aop:aspect>
</aop:config>

配置完成后,Account的service类中的重复代码就可以删除了

public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;
    public IAccountDao getAccountDao() {
        return accountDao;
    }
    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }
    public List<Account> findAllAccount() {
       return accountDao.findAllAccount();

    }
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }
   public void saveAccount(Account account) {

            accountDao.saveAccount(account);

    }
    public void updateAccount(Account account) {

            accountDao.updateAccount(account);

    }
    public void deleteAccount(Integer accountId) {
            accountDao.deleteAccount(accountId);
    }
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("bean开始执行");
            //1.根据名称查询转出账户
            Account source=accountDao.findAccountByName(sourceName);
            //2.根据名称查询转入账户
            Account target=accountDao.findAccountByName(targetName);
            //3.转出账户减前
            source.setMoney(source.getMoney()-money);
            //4.转入账户加钱
            target.setMoney(target.getMoney()+money);
            //5.更新转出账户
            accountDao.updateAccount(source);
            /*int i=1/0;*/
            //6.更新转入账户
            accountDao.updateAccount(target);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值