博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Spring - 08AOP

Posted on 2020-11-18 22:34  Kingdomer  阅读(137)  评论(0编辑  收藏  举报

Spring - 08AOP

(1)AOP简介

(1.1)什么是AOP

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

(1.2)AOP的作用及优势

作用: 在程序运行期间,在不修改源码的情况下对方法进行功能增强
优势: 减少重复代码,提高开发效率,并且便于维护

(1.3)AOP的底层实现

实际上,AOP的底层是通过Spring提供的动态代理技术实现的。
在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的接入,在去调用目标对象的方法,从而完成功能增强。

(1.4)AOP的动态代理技术

  • JDK代理:  基于接口的动态代理技术

  • cglib代理:基于父类的动态代理技术

 (1.5)JDK动态代理实现

// 自定义接口及实现类
public interface TargetInterface {
    void save();
}
//--------------------------------
public class Target implements TargetInterface {

    public void save() {
        System.out.println("Target Save方法执行了......");
    }
}

自定义Advice:

public class Advice {
    public void before(){
        System.out.println("JDK 前置增强......");
    }

    public void afterReturning(){
        System.out.println("JDK 后置增强");
    }
}

 

public class ProxyTest {
    public static void main(String[] args) {
        // 目标对象
        final Target target = new Target();
        // 增强对象
        final Advice advice = new Advice();

        // 返回对象是 动态生成的代理对象
        TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(
                target.getClass().getClassLoader(), // 目标对象类加载器
                target.getClass().getInterfaces(),  // 目标对象相同的接口字节码对象数组
                new InvocationHandler(){  // 调用代理对象的任何方法,实质执行的都是invoke方法
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        advice.before();          // 前置增强
                        Object invoke = method.invoke(target, args); //执行目标方法
                        advice.afterReturning();  // 后置增强
                        return invoke;
                    }
                }
        );
        // 调用代理对象的方法
        proxy.save();
    }
}

 

执行结果:
JDK 前置增强......
Target Save方法执行了......
JDK 后置增强

(1.6)cglib动态代理实现

public class ProxyTest {
    public static void main(String[] args) {
        // 目标对象
        final Target target = new Target();
        // 增强对象
        final Advice advice = new Advice();

        // 返回对象是 动态生成的代理对象 基于cglib
        // 1. 创建增强器
        Enhancer enhancer = new Enhancer();
        // 2. 设置父类(目标)
        enhancer.setSuperclass(Target.class);
        // 3. 设置回调
        enhancer.setCallback(
                new MethodInterceptor() {
                    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                        advice.before();           // 执行前置
                        Object invoke = method.invoke(target, args);   //执行目标
                        advice.afterReturning();   // 执行后置
                        return invoke;
                    }
                }
        );
        // 4. 创建代理对象
        Target proxy = (Target) enhancer.create();

        // 调用代理对象的方法
        proxy.save();
    }
}

(1.7)AOP相关概念

Spring的AOP底层实现就是对上面的动态代理的代码进行了封装,封装后只需要对需要关注的部分进行代码编写。并通过配置的方式完成指定目标的方法增强。
AOP常用术语:
1> Target(目标对象):  代理的目标对象
2> Proxy(代理):       一个类被AOP织入增强后,就产生一个结果代理类
3> Joinpoint(连接点): 指那些被拦截到的点。在Spring中就是方法,Spring只支持方法类型的连接点。
4> Pointcut(切入点):  指要对哪些Joinpoint进行拦截的定义,被增强的方法
5> Advice(通知/增强): 拦截到Joinpoint之后所要做的事情,就是通知
6> Aspect(切面):     就是切入点和通知的结合
7> Weaving(织入):    把增强应用到目标对象来创建新的代理对象的过程。Spring采用动态代理织入,而AsptecJ采用编译期织入和类加载期织入。

(1.8)AOP开发注意事项

1> 需要编写的内容 

   1. 编写核心业务代码(目标类的目标方法)
   2. 编写切面类,切面类中有通知(功能增强方法)
   3. 在配置文件中,配置织入关系,即 将哪些通知与哪些连接点进行结合
2> AOP技术实现的内容
   Spring框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象。
   根据通知类型,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑执行。
3> AOP底层使用哪种代理方式
   在Spring中,框架根据目标类是否实现了接口来决定采用哪种动态代理的方式。 
 

(2)基于XML的AOP开发

(2.1)导入AOP坐标

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>  // 包含了 spring-aop
            <version>5.2.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>

 

(2.2)创建目标接口和目标类(内部有切入点),同上 TargetInterface/Target/ save、delete

(2.3)创建切面类(内部有增强方法)

public class MyAspect {
    public void before(){
        System.out.println("AOP 前置增强......");
    }

    public void afterReturning(){
        System.out.println("AOP 后置增强");
    }

    // ProceedingJoinPoint 正在执行的连接点 -- 切点
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("环绕around 前增强......");
        Object proceed = pjp.proceed();
        System.out.println("环绕around 后增强......");
        return proceed;
    }

    public void afterThrowing(){
        System.out.println("异常抛出增强......");
    }

    public void after(){
        System.out.println("最终增强......");
    }
}

(2.4)将目标类和切面类的对象创建权交给Spring

    <!--目标对象-->
    <bean id="target" class="com.bearpx.sp03aop.aop.Target"></bean>
    <!--切面对象-->
    <bean id="myAspect" class="com.bearpx.sp03aop.aop.MyAspect"></bean>

(2.5)在applicationContext.xml中配置织入关系

引入AOP的命名空间和约束 xmlns:aop="http://www.springframework.org/schema/aop"

    <aop:config>    //配置织入: 告诉Spring框架 哪些方法(切入点)需要进行哪些增强(前置、后置......)
        <aop:aspect ref="myAspect">   // 声明切面
// 切面: 切点+通知 <aop:before method="before" pointcut="execution(public void com.bearpx.sp03aop.aop.Target.save())"></aop:before> <aop:before method="before" pointcut="execution(* com.bearpx.sp03aop.aop.*.*())"></aop:before> <aop:after-returning method="afterReturning" pointcut="execution(* com.bearpx.sp03aop.aop.*.*())"></aop:after-returning> <aop:around method="around" pointcut="execution(* com.bearpx.sp03aop.aop.*.*())"></aop:around> <aop:after-throwing method="afterThrowing" pointcut="execution(* com.bearpx.sp03aop.aop.*.*())"></aop:after-throwing> <aop:after method="after" pointcut="execution(* com.bearpx.sp03aop.aop.*.*())"></aop:after> <!-- 定义pointcut,增强时引用--> <aop:pointcut id="myPointcut" expression="execution(* com.bearpx.sp03aop.aop.*.*())"></aop:pointcut> <aop:around method="around" pointcut-ref="myPointcut"></aop:around> <aop:after method="after" pointcut-ref="myPointcut"></aop:after> </aop:aspect> </aop:config>

(2.6)测试

@RunWith(SpringJUnit4ClassRunner.class)  //pom.xml 添加spring-test坐标
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {

    @Autowired
    private TargetInterface targetInterface;

    @Test
    public void test1(){
        targetInterface.save();
        System.out.println("------------");
        targetInterface.delete();
    }
}

 

(3)配置详解

(3.1)切点表达式的写法

exection([修饰符] 返回值类型 包名.类名.方法名(参数))
   > 访问修饰符可以省略
   > 返回值类型、包名、类名、方法名可以使用星号(*),星号代表任意。
   > 包名与类名之间一个点.代表当前包下的类,两个点..表示当前包及其子包下的类
   > 参数列表可以使用两个点..表示任意个数,任意类型的参数列表
execution(public void com.bearpx.spring.aop.Target.save())
execution(void com.bearpx.spring.aop.Target.*(..))   // Target类下的任意方法(任意参数)
execution(* com.bearpx.spring.aop.*.*(..))           // aop包下的任意类的任意方法(任意参数)
execution(* com.bearpx.spring.aop..*.*(..))          // aop包及其子包下的任意类的任意方法(任意参数)
execution(* *..*.*(..))                              // 任意包下的任意类的任意方法

(3.2)通知的类型

通知的配置语法:
<aop:通知类型 method="切面类中方法名" pointcut="切点表达式"></aop:通知类型>
名称 标签 说明
前置通知 <aop:before> 用于配置前置通知。指定增强的方法在切入点方法之前执行。
后置通知 <aop:after-returning> 用于配置后置通知。指定增强的方法在切入点方法之后执行。
环绕通知 <aop:around> 用于配置环绕通知。指定增强的方法在切入点方法之前和之后都执行。
异常抛出通知 <aop:throwing> 用于配置异常抛出通知。指定增强的方法在出现异常时执行。
最终通知 <aop:after> 用于配置最终通知。无论增强的方法执行是否有异常都会执行。
 
 
 
 
 
 
 
 
 
 
 
 
 

(4)基于注解的AOP开发

(4.1)创建目标接口和目标类

@Component("target")
public class Target implements TargetInterface {
    public void save() {
        System.out.println("Target Save方法执行了......");
    }
    public void delete() {
        System.out.println("Target Delete方法执行了......");
    }
}

(4.2)创建切面类

@Component("myAspect")
@Aspect // 标注当前MyAspect是一个切面类
public class MyAspect {
    public void before(){
        System.out.println("AOP 前置增强......");
    }

    public void afterReturning(){
        System.out.println("AOP 后置增强");
    }

    // ProceedingJoinPoint 正在执行的连接点 -- 切点
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("环绕around 前增强......");
        Object proceed = pjp.proceed();
        System.out.println("环绕around 后增强......");
        return proceed;
    }

    public void afterThrowing(){
        System.out.println("异常抛出增强......");
    }
}

(4.3)将目标类和切面类的对象创建权交给Spring

(4.4)在切面类中使用注解配置织入关系

    @Before("execution(* com.bearpx.sp03aop.aopAnonation.*.*(..))")
    public void before(){
        System.out.println("AOP 前置增强......");
    }

(4.5)在配置文件中开启组件扫描和AOP的自动代理

    // 组件扫描
<context:component-scan base-package="com.bearpx.sp03aop"/> // aop自动代理 <aop:aspectj-autoproxy/>

 

(4.6)测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
public class AopAnnoTest {

    @Autowired
    private TargetInterface target;

    @Test
    public void test1(){
        target.save();
    }
}

 

(5)注解配置详解

(5.1)注解通知的配置语法

@通知注解("切点表达式")
名称 标签 说明
前置通知 @Before 用于配置前置通知。指定增强的方法在切入点方法之前执行。
后置通知 @AfterReturning 用于配置后置通知。指定增强的方法在切入点方法之后执行。
环绕通知 @Around 用于配置环绕通知。指定增强的方法在切入点方法之前和之后都执行。
异常抛出通知 @AfterThrowing 用于配置异常抛出通知。指定增强的方法在出现异常时执行。
最终通知 @After 用于配置最终通知。无论增强的方法执行是否有异常都会执行。
 
 
 
 
 
 
 
 
 
 
 
 
// 正常输出:
Around 环绕 前增强......
Before AOP 前置增强......
Target Save方法执行了......
AfterReturning AOP 后置增强
After 最终增强......
Around 环绕 后增强......

// 异常输出:
Around 环绕 前增强......
Before AOP 前置增强......
AfterThrowing 异常抛出增强......
After 最终增强......

java.lang.ArithmeticException: / by zero

 

(5.2)切点表达式抽取

切点表达式抽取方式: 在切面内定义方法,在方法上使用@Pointcut注解定义切点表达式,然后在增强注解中引用。

    @After("MyAspect.pointcut()")  // 类名.方法名
    public void after(){
        System.out.println("最终增强......");
    }

    @Pointcut("execution(* com.bearpx.sp03aop.aopAnonation.*.*(..))")
    public void pointcut(){}