一、概念
AOP(Aspect Oriented Programming)面向切面编程,是Spring框架中的内容,它是针对于一个事件的某个步骤或阶段,主要应用于:日志,事务处理,异常处理等方面,它的原理是:通过过滤,对指定的一些操作直接添加设定好的方法,不需要频繁的调用,在不使用接口的情况下实现java的动态代理。
OOP面向对象编程,是对事件处理过程中的实体及属性和行为进行抽象和封装,使用OOP也能够实现AOP的方法,但与之相比,OOP在实现这类方法时,每书写一个方法,对其中的操作都需要一个手动的调用,比如说书写日志,我们需要在每个特定的操作后都调用书写日志的这个方法,十分繁琐,使用AOP,就相当于加上了一个过滤器,对整个项目的所有操作进行过滤,在需要的操作前面或后面或周围添加设定好的方法,大幅削减代码的冗余,降低过程中各个部分之间的耦合度,提升开发的效率。
二、以银行的转账业务为例
有以下几个基本步骤:
- 权限验证
- 开启事务处理
- 转账/存钱
- 写入日志
- 提交事务处理
传统的OOP思想是在书写了除转账存钱事件外的其他四个方法之后,每建立一个类似结构的事务,都需要重新调用这四个方法,而AOP思想则是将这四个方法抽离出来,以存钱/取钱方法为切入点,分别在此切入点之前或之后建立配置
实例格式如下:
<?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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="adminCheck" class="cn.zc.dao.Impl.AdminCheck"></bean>
<bean id="transactionManager" class="cn.zc.dao.Impl.TransactionManager"></bean>
<bean id="logInfo" class="cn.zc.dao.Impl.LogInfo"></bean>
<bean id="bankDao" class="cn.zc.dao.Impl.BankDaoImpl">
<!--传统方法的直接调用输出-->
<!--<property name="adminCheck" ref="adminCheck"></property>-->
<!--<property name="transactionManager" ref="transactionManager"></property>-->
</bean>
<!--spring aop面向切面的配置 test2(); aop-->
<aop:config>
<!--切入点 ,切入时机,切入时间-->
<!--切入点,位置和名称-->
<aop:pointcut expression="execution(* cn.zc.dao.Impl.*.*(..))" id="serviceInceptor"></aop:pointcut>
<aop:aspect id="adminInterceptor" ref="adminCheck">
<!--设置切入点之前的方法-->
<aop:before method="check" pointcut-ref="serviceInceptor"></aop:before>
</aop:aspect>
<aop:aspect id="transInterceptor" ref="transactionManager">
<aop:before method="beginTransaction" pointcut-ref="serviceInceptor"></aop:before>
</aop:aspect>
<aop:aspect id="logInterceptor" ref="logInfo">
<aop:after method="writeLog" pointcut-ref="serviceInceptor"></aop:after>
</aop:aspect>
<aop:aspect id="transInterceptor" ref="transactionManager">
<!--<aop:around method="doInceptor" pointcut-ref="serviceInceptor"></aop:around>-->
<aop:after method="commitTransaction" pointcut-ref="serviceInceptor"></aop:after>
</aop:aspect>
</aop:config>
</beans>