理解AOP

AOP全称Aspect Oriented Programming,是面向切面编程的意思。面向对象编程(OOP)支持的是纵向的结构:我们在项目开发中,通常都遵守三层原则,包括控制层(Controller)->业务层(Service)->数据层(dao)的纵向结构,而它具体的某一层就是我们所说的横向。AOP则是OOP的延续,当我们需要为多个对象引入一个公共行为,比如日志,操作记录等,就需要在每个对象中引用公共行为,这样程序就产生了大量的重复代码,大量的重复代码显然不是一个优秀的程序,而AOP则可以完美的解决这个问题:可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。AOP设计模式孜孜不倦追求的是调用者和被调用者之间的解耦,AOP 可以说也是这种目标的一种实现。AOP能够让我们在不影响原有功能的前提下,为软件的横向扩展功能(如:日志记录,性能统计,安全控制,事务处理,异常处理……),它的底层实现是动态代理。下面是AOP的几个概念:

切面(Aspect)

官方的抽象定义为“一个关注点的模块化,这个关注点可能会横切多个对象”。“切面”在ApplicationContext 中来配置。连接点(Joinpoint) :程序执行过程中的某一行为,例如,MemberService.get 的调用或者MemberService.delete 抛出异常等行为。

通知(Advice)

“切面”对于某个“连接点”所产生的动作。其中,一个“切面”可以包含多个“Advice”。

切入点(Pointcut)

匹配连接点的断言,在 AOP 中通知和一个切入点表达式关联。切面中的所有通知所关注的连接点,都由切入点表达式来决定。

目标对象(Target Object)

被一个或者多个切面所通知的对象。当然在实际运行时,SpringAOP 采用代理实现,实际 AOP 操作的是 TargetObject 的代理对象。

AOP 代理(AOP Proxy)

在 Spring AOP 中有两种代理方式,JDK 动态代理和 CGLib 代理。默认情况下,TargetObject 实现了接口时,则采用 JDK 动态代理,反之,采用 CGLib 代理。强制使用 CGLib 代理需要将 的 proxy-target-class 属性设为 true。

通知类型

前置通知(Before Advice)

在某连接点(JoinPoint)之前执行的通知,但这个通知不能阻止连接点前的执行。ApplicationContext中在里面使用元素进行声明。

后置通知(After Advice)

当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。ApplicationContext 中在里面使用元素进行声明。

返回后通知(After Return Advice)

在某连接点正常完成后执行的通知,不包括抛出异常的情况。ApplicationContext 中在里面使用元素进行声明。

环绕通知(Around Advice)

包围一个连接点的通知,类似 Web 中 Servlet 规范中的 Filter 的 doFilter 方法。可以在方法的调用前后完成自定义的行为,也可以选择不执行。ApplicationContext 中在里面使用元素进行声明。例如,ServiceAspect 中的 around 方法。

异常通知(After Throwing Advice)

在 方 法 抛 出 异 常 退 出 时 执 行 的 通 知 。 ApplicationContext 中 在 里 面 使 用元素进行声明。
image.png
在Spring使用AOP,需要导入一个依赖:

  1. <dependency>
  2. <groupId>org.aspectj</groupId>
  3. <artifactId>aspectjweaver</artifactId>
  4. <version>1.9.4</version>
  5. </dependency>

通过 Spring API 实现实现AOP

前置日志实现MethodBeforeAdvice,后置日志实现AfterReturningAdvice接口

  1. package com.wjh.log;
  2. import org.springframework.aop.MethodBeforeAdvice;
  3. import java.lang.reflect.Method;
  4. /**
  5. * @author wjh
  6. * @date 2021/7/17 19:33
  7. * @Package log
  8. */
  9. public class BeforeLog implements MethodBeforeAdvice {
  10. /**
  11. *
  12. * @param method 要执行的目标对象的方法
  13. * @param args 被调用的方法的参数
  14. * @param target 目标对象
  15. * @throws Throwable 异常类型
  16. */
  17. @Override
  18. public void before(Method method, Object[] args, Object target) throws Throwable {
  19. System.out.println("前置日志的method:"+method.getName());
  20. System.out.println( target.getClass().getName() + "的" + method.getName() + "方法被执行了");
  21. for (Object arg : args) {
  22. System.out.println(arg);
  23. }
  24. }
  25. }
package com.wjh.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

/**
 * @author wjh
 * @date 2021/7/17 19:35
 * @Package log
 */
public class AfterLog implements AfterReturningAdvice {
    /**
     *
     * @param returnValue 返回值
     * @param method 被调用的方法
     * @param args 被调用的方法的对象的参数
     * @param target 被调用的目标对象
     * @throws Throwable 异常类型
     */
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("后置置日志的method:"+method.getName());
        System.out.println("执行了" + target.getClass().getName() +"的"+method.getName()+"方法," +"返回值:"+returnValue);
    }
}

测试类

import com.wjh.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author wjh
 * @date 2021/7/17 20:03
 * @Package PACKAGE_NAME
 */
public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        UserService userService=context.getBean("userService",UserService.class);
        userService.add();
    }
}

最后需要在xml中配置实现aop的切入(UserServiceImpl是业务类)

<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--设置支持注解-->
    <context:annotation-config/>

    <!--注册Bean-->
    <bean id="userService" class="com.wjh.service.UserServiceImpl"/>
    <bean id="beforeLog" class="com.wjh.log.BeforeLog"/>
    <bean id="afterLog" class="com.wjh.log.AfterLog"/>

    <!--aop的配置-->
    <aop:config>
        <!--切入点 expression:表达式匹配要执行的方法-->
        <aop:pointcut id="pointcut"
                      expression="execution(* com.wjh.service.UserServiceImpl.*(..))"/>
        <!--执行环绕; advice-ref执行方法,pointcut-ref切入点-->
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

</beans>

运行结果:
image.png

自定义类实现AOP

package com.wjh.log;

/**
 * @author wjh
 * @date 2021/7/19 9:46
 * @Package com.wjh.log
 */
public class MyPointcut {
    public void before(){
        System.out.println("======方法执行前======");
    }

    public void after(){
        System.out.println("======方法执行后======");
    }
}

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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--注册Bean-->
    <bean id="userService" class="com.wjh.service.UserServiceImpl"/>
    <bean id="myPointcut" class="com.wjh.log.MyPointcut"/>

    <!--aop的配置-->
    <aop:config>
        <aop:aspect ref="myPointcut">
            <!--切入点 expression:表达式匹配要执行的方法-->
            <aop:pointcut id="pointcut"
                          expression="execution(* com.wjh.service.UserServiceImpl.*(..))"/>
            <aop:before pointcut-ref="pointcut" method="before"/>
            <aop:after pointcut-ref="pointcut" method="after"/>
        </aop:aspect>
    </aop:config>

</beans>

运行结果:
image.png

使用注解实现AOP

package com.wjh.log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

/**
 * @author wjh
 * @date 2021/7/19 10:17
 * @Package com.wjh.log
 */
@Aspect
public class AnnotationPointcut {
    @Before("execution(* com.wjh.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("---------方法执行前---------");
    }

    @After("execution(* com.wjh.service.UserServiceImpl.*(..))")
    public void after() {
        System.out.println("---------方法执行后---------");
    }

    @Around("execution(* com.wjh.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        System.out.println("签名:" + jp.getSignature());
        //执行目标方法proceed Object proceed = jp.proceed(); System.out.println("环绕后");
    }
}
<bean id="annotationPointcut" class="com.wjh.log.AnnotationPointcut"/> 
<aop:aspectj-autoproxy/>

运行结果:
image.png