AOP面向切面编程

xiaoxiao2021-02-27  172

AOP(面向切面编程)

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,高程序的可重用性,同时提高了开发的效率。

主要功能

日志记录,性能统计,安全控制,事务处理,异常处理等等。

主要意图

将日志记录,性能统计,安全控制,事务处理, 异常处理 等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。

AOP核心概念

1、横切关注点

对哪些方法进行拦截,拦截后怎么处理,这些关注点称之为横切关注点

2、切面(aspect)

类是对物体特征的抽象,切面就是对横切关注点的抽象

3、连接点(joinpoint)

被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法,实际上连接点还可以是字段或者构造器

4、切入点(pointcut)

对连接点进行拦截的定义

5、通知(advice)

所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类

6、目标对象

代理的目标对象

7、织入(weave)

将切面应用到目标对象并导致代理对象创建的过程

8、引入(introduction)

在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段

AOP实例:

创建业务类:

public class SaveService { public void display() { System.out.println("进货"); } } public class SellService { public void display() { System.out.println("销售"); } }

创建切面类:

public class RoleCommon { public void display() { System.out.println("权限检查"); } } public class LogCommon { public void display() { System.out.println("日志检查"); } } 配置xml里面的bean

<?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/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- 将对象加入到bean容器里 --> <!-- 配置业务类的bean --> <bean id="saveService" class="com.jinglin.aop.service.SaveService"></bean> <bean id="sellService" class="com.jinglin.aop.service.SellService"></bean> <!-- 配置切面类的bean --> <bean id="logCommon" class="com.jinglin.aop.common.LogCommon"></bean> <bean id="roleCommon" class="com.jinglin.aop.common.RoleCommon"></bean> <!-- 配置AOP --> <aop:config> <!-- 配置日志切面 --> <aop:aspect id="lole" ref="logCommon"> <!-- 配置连接点的集合 --> <aop:pointcut expression="execution(* com..*.*Service.*(..))" id="loleexecution" /> <!-- 业务执行之前配置增强 --> <aop:before method="display" pointcut-ref="loleexecution" /> </aop:aspect> <!-- 配置权限切面 --> <aop:aspect id="role" ref="roleCommon"> <!-- 配置连接点的集合 --> <aop:pointcut expression="execution(* com..*.*Service.*(..))" id="execution" /> <!-- 业务执行之后配置增强 --> <aop:after method="display" pointcut-ref="execution" /> </aop:aspect> </aop:config> </beans> 编写测试类

public class TestAop { static ClassPathXmlApplicationContext ac = null; static { ac = new ClassPathXmlApplicationContext("applicationContext.xml"); } @Test public void test() { SaveService saveservice = (SaveService) ac.getBean("saveService"); saveservice.display(); SellService sellService = (SellService) ac.getBean("sellService"); sellService.display(); } } 结果

转载请注明原文地址: https://www.6miu.com/read-16607.html

最新回复(0)