Spring AOP

1、什么是AOP

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

img

2、Aop在Spring中的作用

提供声明式事务;允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 ....
  • 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
  • 目标(Target):被通知对象。
  • 代理(Proxy):向目标对象应用通知之后创建的对象。
  • 切入点(PointCut):切面通知 执行的 “地点”的定义。
  • 连接点(JointPoint):与切入点匹配的执行点。

img

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice

img

即 Aop 在 不改变原有代码的情况下 , 去增加新的功能。

3、使用Spring实现Aop

【重点】使用AOP织入,需要导入一个依赖包!

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.9.4</version>
</dependency>

我们有三种方式实现AOP,分别如下:

3.1、使用Spring的API接口

具体方式

  1. 编写业务接口和对应的实现类

    public interface UserService {
        void insert();
        void delete();
        void update();
        void query();
    }
    
    public class UserServiceImpl implements UserService {
        @Override
        public void insert() {
            System.out.println("新增一个用户");
        }
    
        @Override
        public void delete() {
            System.out.println("删除一个用户");
        }
    
        @Override
        public void update() {
            System.out.println("更新一个用户");
        }
    
        @Override
        public void query() {
            System.out.println("查询一个用户");
        }
    }
    
  2. 编写两个增强类,前置和后置增强

    public class BeforeLog implements MethodBeforeAdvice {
        /**
         * 前置增强方法
         * @param method 要执行的目标对象的方法
         * @param args   方法的参数
         * @param target 目标对象
         * @throws Throwable
         */
        @Override
        public void before(Method method, Object[] args, Object target) throws Throwable {
            System.out.println(target.getClass().getName() + "的" + method.getName() + "被执行了!");
        }
    }
    
    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.getName() + "方法,返回结果为:" + returnValue);
        }
    }
    
  3. 编写Spring的配置文件,实现AOP切入

    <?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
           https://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <!-- 注册Bean -->
        <bean id="userService" class="com.jh.service.UserServiceImpl"/>
        <bean id="beforeLog" class="com.jh.log.BeforeLog"/>
        <bean id="afterLog" class="com.jh.log.AfterLog"/>
    
        <!-- 配置AOP:需要导入AOP的约束 -->
        <aop:config>
            <!-- 切入点; expression:表达式匹配要执行的方法 -->
            <!-- 表达式:
                第一个*:表示方法的返回值为所有类型
                包名.*:表示这个包下的所有类
                类名.*:表示这个类下的所有方法
                (..):表示方法的参数为任意类型,参数可有可无
            -->
            <aop:pointcut id="pointcut" expression="execution(* com.jh.service.*.*(..))"/>
            <!-- 执行环绕; advice-ref 执行的方法。pointcut-ref 切入点 -->
            <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
        </aop:config>
    </beans>
    
  4. 测试

    @Test
    public void test01() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 注入AOP底层是代理模式,需要的是接口,所有用UserService接收Bean,而不是UserServiceImpl
        UserService service = (UserService) context.getBean("userService");
        service.insert();
    }
    

    image-20210121230431693

AOP的重要性:很重要,一定要理解其中的思路,主要是思想的理解这一块。

Spring的AOP就是将公共的业务 (日志,安全等) 和领域业务结合起来,当执行领域业务时,将会把公共业务加进来。实现公共业务的重复利用,领域业务更纯粹,程序猿专注领域业务,其本质还是动态代理。

3.2、自定义类实现AOP

目标业务类不变依旧是上面userServiceImpl

具体步骤:

  1. 编写一个自己的切入方法

    public class DiyPointCut {
        public void before(){
            System.out.println("方法执行前");
        }
        public void after(){
            System.out.println("方法执行后");
        }
    }
    
  2. 编写配置文件

    <!-- 在容器中注入自定义的切入方法 -->
    <bean id="diy" class="com.jh.diy.DiyPointCut"/>
    <aop:config>
        <!-- 自定义切面:ref要引入的自定义类 -->
        <aop:aspect ref="diy">
            <!-- 切入点 -->
            <aop:pointcut id="point" expression="execution(* com.jh.service.UserServiceImpl.*(..))"/>
            <!-- 需要切入的方法; method:自定义类的方法 -->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
    
  3. 测试方法不变,查看输出

    @Test
    public void test01() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService service = (UserService) context.getBean("userService");
        service.insert();
    }
    

    image-20210121231827080

3.3、使用注解实现AOP

  1. 编写一个注解实现的增强类

    // 标注这个类是一个切面
    @Aspect
    public class AnnotationPointCut {
    
        @Before("execution(* com.jh.service.UserServiceImpl.*(..))")
        public void before() {
            System.out.println("方法执行前");
        }
    
        @After("execution(* com.jh.service.UserServiceImpl.*(..))")
        public void after() {
            System.out.println("方法执行后");
        }
    
        // 在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点;
        @Around("execution(* com.jh.service.UserServiceImpl.*(..))")
        public void around(ProceedingJoinPoint joinPoint) throws Throwable {
            System.out.println("环绕前");
            System.out.println("获得的签名:" + joinPoint.getSignature());
            //执行目标方法proceed
            Object proceed = joinPoint.proceed();
            System.out.println("环绕后");
            System.out.println(proceed);
        }
    }
    
  2. 编写配置文件

    <!-- 将类注册到Spring容器,也可以使用@Component -->
    <bean id="annotationPointCut" class="com.jh.diy.AnnotationPointCut"/>
    <!-- 开启AOP注解支持 -->
    <aop:aspectj-autoproxy/>
    
  3. 测试

    @Test
    public void test01() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService service = (UserService) context.getBean("userService");
        service.insert();
    }
    

    image-20210121235009123

通过aop命名空间的<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。
当然,spring 在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,
但具体实现的细节已经被<aop:aspectj-autoproxy />隐藏起来了

<aop:aspectj-autoproxy />有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,
当配为<aop:aspectj-autoproxy  poxy-target-class="true"/>时,表示使用CGLib动态代理技术织入增强。
不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。
懂不懂,都是收获
原文地址:https://www.cnblogs.com/paidaxing0623/p/14312614.html