AOP是对目标方法进行增强,的本质是代理开发模式。什么是代理开发模式?
代理开发模式:
举个例子:假设我要送一个人礼物,但是不好意思送,这时我会请别人帮我送,这个人被成为代理对象,而我要送的人为目标对象。
应用这个场景,当我们创建user对象,需要调用这个对象里的add()方法,不是我们手动调用,而是需要调用其他类中方法帮助我们调用,这就是代理开发;
这个帮助我们调用user对象方法的类,不需要我们手动去写,jdk和Spring帮助我们写好了
一个是基于jdk给我们提供的,但需要实现接口,一个是Spring帮助我们提供的,但是需要实现继承。
如何去用呢?
1、导入对应坐标
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
2、准备目标对象和接口
public class Target implements TargetInterface{
public void method(){
System.out.println("普通方法执行了");
}
public interface TargetInterface {
void method();
}
注意:接口中的方法与目标对象一致
3、准备增强类(对目标方法进行增强)
public void before(){
System.out.println("前置方法执行了.....");
}
public void return(){
System.out.println("后置方法执行了.....");
}
public void around(ProceedingJoinPoint point) throws Throwable{
System.out.println("环绕前执行了.....");
Object proceed =point.proceed();
System.out.println("环绕后执行了.....");
}
public void throwing(){ //----->在目标对象异常执行
System.out.println("异常方法执行了.....");
}
public void after(){ //相当于finally
System.out.println("前置方法执行了.....");
}
4、将目标对象,增强对象放入Spring容器中
<bean class="com.NEPU.Aop.Target" id="target"></bean>
<bean class="com.NEPU.Aop.MyTarget" id="myTarget"></bean>
5、织入
<aop:config>
<aop:aspect ref="谁是增强对象">
<aop:before method="增强方法名" pointcut="execution("增强哪个方法")"
</aop:aspect> <!--前置增强 -->
<aop:after-returning method="增强方法名" pointcut="execution("增强哪个方法")"
</aop:aspect> <!-- 后置增强-->
<aop:around method="增强方法名" pointcut="execution("增强哪个方法")"
</aop:aspect> <!--环绕增强-->
<aop:after-throwing method="增强方法名" pointcut="execution("增强哪个方法")"
</aop:aspect> <!--异常增强-->
<aop:after method="增强方法名" pointcut="execution("增强哪个方法")"
</aop:aspect> <!--最终增强-->
</aop:aspect>
</aop:config>
连接点:目标对象的所有方法都是连接点
切入点:目标对象的所调用方法是切入点
增强/通知:增强方法中的方法体
切面:整个方法--方法名加方法体
织入:动态代理实现的过程
本文章只是作者对Spring的理解,希望能帮助到大家,后续还会接着更新