Spring之详解如何实现AOP

1,Spring中AOP的实现

1.1 什么是AOP

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

Spring中AOP的底层实现就是靠动态代理,动态代理的底层实现就是靠java中的反射。

1.2 AOP的作用

提供声明式事务,允许用户自定义切面。
在这里插入图片描述

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

在这里插入图片描述

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:(即AOP 在不改变原有代码的情况下 , 去增加新的功能)

通知类型连接点实现接口
前置通知方法前org.springframework.aop.MethodBeforeAdvice
后置通知方法后org.springframework.aop.AfterReturningAdvice
环绕通知方法前后org.aopalliance.intercept.MethodInterceptor
异常抛出通知方法抛出异常org.springframework.aop.ThrowsAdvice
引介通知类中增加新的方法属性org.springframework.aop.IntroductionInterceptor

1.3 Spring中实现AOP

1.3.1 使用Spring的API接口

首先,使用AOP织入,需要导入依赖

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

之后就是代码实现:

1,业务接口代码:

public interface UserService {

   public void add();

   public void delete();

   public void update();

   public void select();

}

2,接口实现类代码:

package com.wang.service;

public class UserServiceImpl implements UserService{

    @Override
    public void add() {
        System.out.println("增加用户");
    }

    public void delete() {
        System.out.println("删除用户");
    }

    public void update() {
        System.out.println("更新用户");
    }

    public void select() {
        System.out.println("查询用户");
    }
}

3,两个增强类日志代码,一个前置一个后置。前置实现MethodBeforeAdvice接口,后置实现AfterReturningAdvice接口

public class Log implements MethodBeforeAdvice {

   //method : 要执行的目标对象的方法
   //objects : 被调用的方法的参数
   //Object : 目标对象
   @Override
   public void before(Method method, Object[] objects, Object o) throws Throwable {
       System.out.println( o.getClass().getName() + "的" + method.getName() + "方法被执行了");
  }
}
package com.wang.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
    //returnValue 返回值
    //method被调用的方法
    //args 被调用的方法的对象的参数
    //target 被调用的目标对象
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        //利用java底层的反射实现
        System.out.println("执行了" + target.getClass().getName()
                +"的"+method.getName()+"方法,"
                +"返回值:"+returnValue);
    }
}

4,在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
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--注册bean-->
    <bean id ="userService" class="com.wang.service.UserServiceImpl"></bean>
    <bean id = "log" class="com.wang.log.Log"/>
    <bean id="AfterLog" class="com.wang.log.AfterLog"/>

    <!--aop的配置-->
    <aop:config>
        <!--切入点 expression:表达式匹配要执行的方法,表示com.wang.service包下的.UserServiceImpl类下的任意参数的任意方法-->
        <aop:pointcut id="pointcut" expression="execution(* com.wang.service.UserServiceImpl.*(..))"/>
        <!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="AfterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

5,进行测试

import com.wang.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.select();
    }
}

测试结果:

在这里插入图片描述

1.3.2 自定义实现(切面定义

1,手动写一个切入类:相当于是不使用已有的MethodBeforeAdvice接口和AfterReturningAdvice接口

package com.wang.diy;

public class WangPointCut {
    public void before() {
        System.out.println("==========方法执行前============");
    }

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

2,将我们写的配置类在spring中配置

<?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-->
    <bean id ="userService" class="com.wang.service.UserServiceImpl"></bean>
    <bean id = "log" class="com.wang.log.Log"/>
    <bean id="AfterLog" class="com.wang.log.AfterLog"/>

    <bean id="diy" class="com.wang.diy.WangPointCut"/>
    <!--aop的配置-->
    <aop:config>
        <!--自定义切面,ref要引用的类-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.wang.service.UserServiceImpl.*(..))"/>
            <!--这里的方法是我们自定义WangPointCut中实现的方法-->
            <aop:before method="before" pointcut-ref="point"></aop:before>
            <aop:after method="after" pointcut-ref="point"></aop:after>
        </aop:aspect>
    </aop:config>

</beans>

3,测试类同上

测试结果:

在这里插入图片描述

1.3.3 使用注解实现

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

package com.wang.diy;


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;

@Aspect
public class AnnotationPointCut {
    @Before("execution(* com.wang.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("==========方法执行前============");
    }

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

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    @Around("execution(* com.wang.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("==========环绕前============");

        //获取签名
        //Signature signature = jp.getSignature();
        //System.out.println("signature:" + signature);

        //执行方法
        Object proceed = jp.proceed();

        System.out.println("==========环绕后============");
    }
}

2,在Spring配置文件中,注册bean,并增加支持注解的配置。

<?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-->
    <bean id ="userService" class="com.wang.service.UserServiceImpl"></bean>
    
    <!--方式三:注解-->
    <bean id="annotationPointCut" class="com.wang.diy.AnnotationPointCut"></bean>
        <!--开启注解支持: JDK(默认proxy-target-class="false") cglib-->
    <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

</beans>

3,测试代码同上

输出结果:

在这里插入图片描述
通过输出结果我们可以发现,@Around先执行,之后Object proceed = jp.proceed();执行方法,执行方法前调用@Before

以上就是Spring中实现AOP 的三种方法。

作者:王二黑_Leon
欢迎任何形式的转载,但请务必注明出处。
文章为学习狂神说Java《Spring-5》的笔记
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王小二_Leon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值