IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> 【Spring】实现AOP的三种方式(Spring的AIP接口、自定义、注解) -> 正文阅读

[Java知识库]【Spring】实现AOP的三种方式(Spring的AIP接口、自定义、注解)

前提须知

什么是AOP:

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。

AOP的作用:

利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。

说白了,AOP的作用就是降低业务的耦合度,使得每一个业务的核心代码更加纯粹,更加专注。其作用和动态代理很相似。

相关名词:

目标(target): 被通知的对象(可理解为被代理的类,与“切入点”很像)

代理(proxy):目标被通知之后生成的一个新的对象,它将代替目标对象完成响应的事情

通知(advice):切面必须要完成的工作,说白了是类中的一个方法(实现了Spring的API接口的类)

切入点(pointCut):切面通知执行的“地点”(可理解为被代理的类或方法)

连接点(jointPoint):与切入点匹配的执行点(可以理解为被代理类中的方法)

切面(aspect):横切关注点 被模块化的特殊对象,其实就是一个类(可以理解为自定义类)

注:如果你没有看过动态代理【点击查看】,那么你应该先去看看动态代理。

公共类和接口
接口:

public interface UserService {
    void add();
    void delete();
    void update();
    void select();
}

实现类:

public class UserServiceImp implements UserService {
    public void add() {
        System.out.println("成功添加了一名用户");
    }

    public void delete() {
        System.out.println("成功删除了一名用户");
    }

    public void update() {
        System.out.println("成功的更新了一名用户");
    }

    public void select() {
        System.out.println("成功的查询了一名用户");
    }
}

方式一:使用Spring的API接口

我们会用到一下两个接口:

MethodBeforeAdvice
类(A)实现该接口后,当一个 “业务类的中方法” 被绑定成 “切入点” 后,该类中的方法在被执行前,会先执行A类中的重写方法。

AfterReturningAdvice
类(A)实现该接口后,当一个 “业务类的中方法” 被绑定成 “切入点” 后,该类中的方法在被执行后,会再执行A类中的重写方法。


【创建实现上述两个接口的类并重写其中的方法】

实现MethodBeforeAdvice的类:

public class BeforeLog implements MethodBeforeAdvice {

    /**
     * @param method the method being invoked
     * @param args the arguments to the method
     * @param target the target of the method invocation. May be {@code null}.
     * @throws Throwable if this object wishes to abort the call.
     */
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(method.getName()+"方法被执行了!");
    }
}

实现了AfterReturningAdvice接口的类

public class AfterLog implements AfterReturningAdvice {

    /**
     * @param returnValue the value returned by the method, if any
     * @param method the method being invoked
     * @param args the arguments to the method
     * @param target the target of the method invocation. May be {@code null}.
     * @throws Throwable if this object wishes to abort the call.
     */
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(method.getName()+"方法被执行完毕! 返回值为"+returnValue);
    }
}

【创建applicationContext.xml配置文件并配置bean和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
        https://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.sdpei.service.UserServiceImp"/>
    <bean id="beforeLog" class="com.sdpei.log.BeforeLog"/>
    <bean id="afterLog" class="com.sdpei.log.AfterLog"/>

    <!--配置aop-->
    <aop:config>
        <!--配置切入点:execution(*  表示任意
                                com.sdpei.service.UserServiceImp.*(..) 表示UserServiceImp中的所有方法,(..)表示参数任意
                                )-->
        <aop:pointcut id="pointcut" expression="execution(* com.sdpei.service.UserServiceImp.*(..))"/>

        <!--添加顾问-->
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

    </aop:config>
    
 </beans>

在这里插入图片描述


测试:

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

        //注意这里要强转成接口,代理的是一类接口
        UserService userService = context.getBean("userService", UserService.class);

        userService.add();
    }
}

在这里插入图片描述


方式二:使用自定义"切面"

我们也可以不使用Spring的API接口,可以自定义“切面”。但是如果是自定义“切面”,那么就不容易获得target的一些信息了(例如:方法名、参数、接口名…)。

上述所说的“切面”,其实就是一个类。我们可以在配置文件中将其配成AOP的形式。

第一步:自定义切面

public class MyAOP {
    public void before(){
        System.out.println("方法开始执行...");
    }


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

}

第二步:配置配置文件,使其成为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
        https://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.sdpei.service.UserServiceImp"/>
    <bean id="myaop" class="com.sdpei.myAOP.MyAOP"/>
    
     <aop:config>
            <!--实现切面-->
            <aop:aspect ref="myaop">
                <aop:pointcut id="point" expression="execution(* com.sdpei.service.UserServiceImp.*(..))"/>
                <aop:before method="before" pointcut-ref="point"/>
                <aop:after method="after" pointcut-ref="point"/>
            </aop:aspect>
        </aop:config>
</beans>

在这里插入图片描述

第三步:测试

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

        //注意这里要强转成接口,代理的是一类接口
        UserService userService = context.getBean("userService", UserService.class);

        userService.add();
    }
}

在这里插入图片描述


方式三:使用注解

使用注解是极其方便的,其不需要过多繁琐的配置文件,简化开发。

我们在这里会使用的几个基本的注解:
@Aspect:其作用相当于<aop:aspect ref="…">

@Before:其作用相当于 <aop:before method="…" pointcut-ref="…"/>

@After:其作用相当于<aop:after method="…" pointcut-ref="…"/>

@Around:其作用相当于<aop:around method="" pointcut-ref="" />

第一步:创建自定义类并使用注解:

@Aspect
public class AnnoAOP {
    @Before("execution(* com.sdpei.service.UserServiceImp.*(..))")
    public void before(){
        System.out.println("###########方法开始执行前############");
    }

    @After("execution(* com.sdpei.service.UserServiceImp.*(..))")
    public void after(){
        System.out.println("###########方法执行结束后############");
    }

    @Around("execution(* com.sdpei.service.UserServiceImp.*(..))")
    public void around(ProceedingJoinPoint pjp){
        try {
            System.out.println("环绕方法执行前...");
            Object proceed = pjp.proceed();
            System.out.println("环绕方法执行后...");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}

第三步:设置相关的配置文件:

<?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
        https://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.sdpei.service.UserServiceImp"/>
    <bean id="annoAOP" class="com.sdpei.annotation.AnnoAOP"/>
    
<!-- 开启自动代理。 默认是JDK(proxy-target-class="false") 设置cglib(proxy-target-class="true")   -->
    <aop:aspectj-autoproxy proxy-target-class="false"/>

</beans>

注意:使用注解需要开启自动代理。

<aop:aspectj-autoproxy proxy-target-class="false"/>

第四步:测试

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

        //注意这里要强转成接口,代理的是一类接口
        UserService userService = context.getBean("userService", UserService.class);

        userService.add();
    }
}

在这里插入图片描述我们可以发现around是包在before和after外面的。


注意事项

  1. 在配置文件的< beans>中添加了
    在这里插入图片描述
  1. 在使用注解的时候,不要忘记开启自动代理。
    在这里插入图片描述
  1. 不要忘记导入maven依赖
    在这里插入图片描述
  1. 注意在测试的时候,获取bean(getBean())的方法的返回值要强转成接口,代理的是一类接口
    在这里插入图片描述
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-07-04 19:22:40  更:2021-07-04 19:23:21 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/5 6:25:40-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码