版权声明:未经作者允许,禁止私自转载! https://blog.csdn.net/qq_42726314/article/details/82855500
一.AOP概念:
面向切面编程,指扩展功能的同时不修改源代码,将功能代码聪业务逻辑中分离出来。
主要功能:日志记录、性能统计、事务处理、安全控制、异常处理等。
主要意图:将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。
二、AOP特点:
采用横向抽取机制,取代了传统纵向继承体系重复性代码。
三、AOP底层实现:
AOP底层使用动态代理实现。包括两种方式:
-
(1)使用JDK动态代理实现。
-
(2)使用cglib来实现
四、AOP操作术语:
- Joinpoint(连接点): 类里面可以被增强的方法,这些方法称为连接点。
- Pointcut(切入点):所谓切入点是指我们要对哪些Joinpoint进行拦截的定义。
- Advice(通知/增强):所谓通知是指拦截到Joinpoint之后所要做的事情就是通知.通知分为前置通知,后置通知,异常通知,最终通知,环绕通知(切面要完成的功能)。
- Aspect(切面):是切入点和通知(引介)的结合。
- Introduction(引介):引介是一种特殊的通知在不修改类代码的前提下, Introduction可以在运行期为类动态地添加一些方法或Field。
- Target(目标对象):代理的目标对象(要增强的类)。
- Weaving(织入):是把增强应用到目标的过程,把advice 应用到 target的过程。
- Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类。
五、一个简单的AOP示例:
所需jar:aop.zip 密码:2t03
spring配置文件:springConfig.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
">
<bean id="target" class="aop.Target"></bean>
<bean id="adviceTarget" class="aop.AdviceTarget"></bean>
<!-- 配置aop操作 -->
<aop:config>
<!-- 配置切入点 -->
<aop:pointcut expression="execution(public void helloAop())" id="pointcut"/>
<!-- 配置切面-->
<aop:aspect ref="adviceTarget">
<!-- 配置增强类型 -->
<aop:before method="before" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
</beans>
实体类:Target.java
package entity;
public class Target {
public void helloAop() {
System.out.println("增强!");
}
}
工具类:AdviceTarget.java
package aop;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
public class AdviceTarget {
public void before(JoinPoint jp) {
System.out.println("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法。方法入参:"+Arrays.toString(jp.getArgs()));
}
}
junit测试:
@Test
public void testAop() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springConfig.xml");
Target target = (Target)context.getBean("target");
System.out.println(target);
}
测试结果: