初学Spring之 AOP 面向切面编程

AOP(Aspect Oriented Programming)面向切面编程

通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术

是面向对象(OOP)的延续

AOP 在 Spring 中的作用:

1.提供声明式事务

2.允许用户自定义切面

导入 jar 包,搜索 AspectJ Weaver

(复制过来把 <scope>runtime</scope> 这行删去,不然注解报错)

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.22.1</version>
    </dependency>

方法一:使用原生 Spring API 接口实现

先写个 UserService 接口:

package com.demo.service;

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

再写个 UserServiceImpl 类来实现接口,重写方法

package com.demo.service;

public class UserServiceImpl implements UserService{
    @Override
    public void add() {
        System.out.println("增");
    }

    @Override
    public void delete() {
        System.out.println("删");
    }

    @Override
    public void update() {
        System.out.println("改");
    }

    @Override
    public void select() {
        System.out.println("查");
    }
}

写个 Log 类来实现 MethodBeforeAdvice 接口(前置日志)

method:要执行的目标对象的方法

args:参数

target:目标对象

package com.demo.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {

    /*
    method:要执行的目标对象的方法
    args:参数
    target:目标对象
     */
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"方法被执行了");
    }
}

再写个 AfterLog 类来实现 AfterReturningAdvice 接口(后置日志)

returnValue 返回值

package com.demo.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {

    //returnValue返回值
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
    }
}

配置 applicationContext.xml 文件

注册 bean

配置 aop:需要导入 aop 的约束

xmlns:aop="http://www.springframework.org/schema/aop"

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd

使用原生 Spring API 接口

<aop:config>

 切入点:expression:表达式,execution(要执行的位置:修饰词 返回值 类名 方法名 参数)

<aop:pointcut id="xx" expression="execution(* com.demo.service.UserServiceImpl.*(..))"/>

执行环绕增加

<aop:advisor advice-ref="xx" pointcut-ref="xx"/>

<?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"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       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
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
						http://www.springframework.org/schema/util
						http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 注册bean -->
    <bean id="user" class="com.demo.service.UserServiceImpl"/>
    <bean id="log" class="com.demo.log.Log"/>
    <bean id="afterLog" class="com.demo.log.AfterLog"/>

    <!-- 使用原生Spring API接口 -->
    <!-- 配置aop:需要导入aop的约束 -->
    <aop:config>
        <!-- 切入点:expression:表达式,execution(要执行的位置:修饰词 返回值 类名 方法名 参数) -->
        <aop:pointcut id="pointcut" expression="execution(* com.demo.service.UserServiceImpl.*(..))"/>

        <!-- 执行环绕增加 -->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

</beans>

写个测试类

动态代理,代理的是接口

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

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理,代理的是接口
        UserService userService = (UserService) context.getBean("user");
        userService.add();
    }
}

执行结果如下:

方法二:自定义类来实现 AOP(切面定义)

增加一个自定义的类

package com.demo.pointcut;

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

    public void after(){
        System.out.println("方法执行后");
    }
}
<?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"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       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
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
						http://www.springframework.org/schema/util
						http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 注册bean -->
    <bean id="user" class="com.demo.service.UserServiceImpl"/>
    <bean id="log" class="com.demo.log.Log"/>
    <bean id="afterLog" class="com.demo.log.AfterLog"/>

    <!-- 自定义类 -->
    <bean id="diy" class="com.demo.pointcut.PointCut"/>

    <aop:config>
        <!-- 自定义切面,ref:要引用的类 -->
        <aop:aspect ref="diy">
            <!-- 切入点 -->
            <aop:pointcut id="pointcut" expression="execution(* com.demo.service.UserServiceImpl.*(..))"/>
            <!-- 通知 -->
            <aop:before method="before" pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

</beans>

 自定义切面,ref:要引用的类

<aop:aspect ref="xx">

切入点:

<aop:pointcut id="pointcut" expression="execution(* com.demo.service.UserServiceImpl.*(..))"/>

通知:

<aop:before method="xx" pointcut-ref="xx"/>

测试类不变,执行结果如下:

方法三:使用注解实现 AOP

注意导入包不要导错

package com.demo.pointcut;

//使用注解方式实现AOP
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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.demo.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法执行前");
    }

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

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

        Signature signature = joinPoint.getSignature(); //获得签名
        System.out.println(signature);

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

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

        System.out.println(proceed);
    }
}

开启注解支持:<aop:aspectj-autoproxy/>

<?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"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       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
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
						http://www.springframework.org/schema/util
						http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 注册bean -->
    <bean id="user" class="com.demo.service.UserServiceImpl"/>
    <bean id="log" class="com.demo.log.Log"/>
    <bean id="afterLog" class="com.demo.log.AfterLog"/>

    <bean id="anno" class="com.demo.pointcut.AnnotationPointCut"/>
    <!-- 开启注解支持 -->
    <aop:aspectj-autoproxy/>
    
</beans>

测试类不变,执行结果如下:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/780116.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Java 基础--File - IO流(2)

I/O流 定义 数据从硬盘流向内存为输入流&#xff0c;数据从内存流向硬盘为输出流。输入也叫读取数据&#xff0c;输出也叫写出数据。 IO分类 1.按照数据的流向分为&#xff1a;输入流和输出流 ①输入流&#xff1a;把数据从其他设备上读取到内存中的流 ②输出流&#xff1…

pdf怎么转换成图片格式文件,pdf文档怎么转换成图片格式

在数字化时代&#xff0c;pdf文件转换成图片格式是一种常见的操作&#xff0c;无论是在工作还是日常生活中&#xff0c;我们总会遇到需要将pdf文件转换为图片的需求。这可能是因为图片格式更易于分享、展示或编辑。那么&#xff0c;如何高效地将pdf转换成图片呢&#xff1f;本文…

240705_昇思学习打卡-Day17-基于 MindSpore 实现 BERT 对话情绪识别

240705_昇思学习打卡-Day17-基于 MindSpore 实现 BERT对话情绪识别 近期确实太忙&#xff0c;此处仅作简单记录&#xff1a; 模型简介 BERT全称是来自变换器的双向编码器表征量&#xff08;Bidirectional Encoder Representations from Transformers&#xff09;&#xff0c…

#数据结构 顺序表

线性表 顺序表 每种结构都有它存在意义 线性表的顺序存储实现指的是用一组连续的存储单元存储线性表的数据元素。 概念 顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性表&#xff0c;一般情况下采用数组存储。在数组上完成数据的增查改删。 逻辑结构&#…

阶段三:项目开发---大数据开发运行环境搭建:任务8:安装配置Redis

任务描述 知识点&#xff1a;安装配置Redis 重 点&#xff1a; 安装配置Redis 难 点&#xff1a;无 内 容&#xff1a; Redis&#xff08;Remote Dictionary Server )&#xff0c;即远程字典服务&#xff0c;是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可…

数据结构1:C++实现变长数组

数组作为线性表的一种&#xff0c;具有内存连续这一特点&#xff0c;可以通过下标访问元素&#xff0c;并且下标访问的时间复杂的是O(1)&#xff0c;在数组的末尾插入和删除元素的时间复杂度同样是O(1)&#xff0c;我们使用C实现一个简单的边长数组。 数据结构定义 class Arr…

【手写数据库内核组件】01 解析树的结构,不同类型的数据结构组多层的链表树,抽象类型统一引用格式

不同类型的链表 ​专栏内容&#xff1a; postgresql使用入门基础手写数据库toadb并发编程 个人主页&#xff1a;我的主页 管理社区&#xff1a;开源数据库 座右铭&#xff1a;天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物. 文章目录 不同类型…

图像基础知识

图像卷积 卷积(convolution)是通过两个函数f和g生成第三个函数的一种数学算子,表征函数f与g经过翻转和平移的重叠部分的面积。 卷积概念是两个变量在某范围内相乘后求和的结果。图像处理中的卷积概念:数字图像是一个二维的离散信号,对数字图像做卷积操作其实就是利用卷积…

【帧中继实验-ensp】

实验要求 在R1上开启一个点对点子接口&#xff0c;用于连接 R1–R2&#xff0c;两端IP地址为12.1.1.x 。开启一个多点子接口 &#xff0c;用于连接R1–R3&#xff0c;R4&#xff0c;两段IP地址为134.1.1.x。 具体DLCI分配和映射关系如下&#xff1a; R1 102 R2 201—动态映射…

华为OD机试 - 来自异国的客人(Java 2024 D卷 100分)

华为OD机试 2024D卷题库疯狂收录中&#xff0c;刷题点这里 专栏导读 本专栏收录于《华为OD机试&#xff08;JAVA&#xff09;真题&#xff08;D卷C卷A卷B卷&#xff09;》。 刷的越多&#xff0c;抽中的概率越大&#xff0c;每一题都有详细的答题思路、详细的代码注释、样例测…

使用Github Actions自建Docker镜像仓库

使用Github Actions自建Docker镜像仓库 背景使用Github Actions自建Docker镜像仓库fork项目[docker_image_sync](https://github.com/xqxyxchy/docker_image_sync)获取云厂商容器镜像服务信息配置github secrets运行github action配置需要同步的镜像同步后效果华为云配置 背景 …

机器学习简介--NLP(二)

机器学习简介 机器学习简介机器学习例子机器学习分类有监督学习有监督学习的应用 无监督学习 机器学习常见概念数据集k折交叉验证过拟合欠拟合评价指标 机器学习简介 机器学习例子 问题&#xff1a; 2&#xff0c;4&#xff0c;6&#xff0c;8&#xff0c;&#xff1f;&#…

深入理解JS逆向代理与环境监测

博客文章&#xff1a;深入理解JS逆向代理与环境监测 1. 引言 首先要明确JavaScript&#xff08;JS&#xff09;在真实网页浏览器环境和Node.js环境中有很多使用特性的区别。尤其是在环境监测和对象原型链的检测方面。本文将探讨如何使用JS的代理&#xff08;Proxy&#xff09…

2024亚太杯中文赛数学建模B题word+PDF+代码

2024年第十四届亚太地区大学生数学建模竞赛&#xff08;中文赛项&#xff09;B题洪水灾害的数据分析与预测&#xff1a;建立指标相关性与多重共线性分析模型、洪水风险分层与预警评价模型、洪水发生概率的非线性预测优化模型&#xff0c;以及大规模样本预测与分布特征分析模型 …

算法011:最大连续的1的个数

最大连续的1的个数. - 备战技术面试&#xff1f;力扣提供海量技术面试资源&#xff0c;帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/max-consecutive-ones-iii/ 乍一看&#xff0c;这道题很奇怪&#xff0c;什么叫最多翻转k个0&a…

自动控制:反馈控制

自动控制&#xff1a;反馈控制 反馈控制&#xff08;Feedback Control&#xff09;是一种在控制系统中通过测量输出信号&#xff0c;并将其与期望信号进行比较&#xff0c;产生误差信号&#xff0c;再根据误差信号调整输入来达到控制目标的方法。反馈控制是自动控制系统中最常…

揭秘Conda:Python开发者必备的包管理神器

conda 简介 Conda 是一个开源的包管理系统和环境管理系统&#xff0c;用于安装和管理软件包以及创建和维护不同的软件环境。 它最初是为 Python 语言设计的&#xff0c;但现在已经支持多种编程语言&#xff0c;包括 R、Ruby、Lua、Scala 等。 1、Anaconda&#xff1a;是一个…

HCIE之IPV6和OSPFv6(十四)

IPV6 1、IPv6基础1.1 Ipv6地址静态配置、Eui 641.1.1 Ipv6地址静态配置1.1.2、Ipv6地址计算总结1.1.2.1、IEEE eui 64计算1.1.2.1.1、作用1.1.2.1.2、计算方法1.1.2.1.3、计算过程 1.1.2.2、被请求加入的组播组地址计算&#xff08;三层&#xff09;1.1.2.2.1、 作用1.1.2.2.2、…

在pycharm里如何使用Jetbrains AI Assistant

ai assistant激活成功后&#xff0c;如图 ai assistant渠道&#xff1a;https://web.52shizhan.cn/activity/ai-assistant 在去年五月份的 Google I/O 2023 上&#xff0c;Google 为 Android Studio 推出了 Studio Bot 功能&#xff0c;使用了谷歌编码基础模型 Codey,Codey 是…

浪潮信息元脑服务器支持英特尔®至强®6能效核处理器 展现强劲性能

如今&#xff0c;服务器作为数字经济的核心基础设施&#xff0c;正面临着前所未有的挑战和机遇。作为服务器领域的领军企业&#xff0c;浪潮信息始终站在行业前沿&#xff0c;不断推陈出新&#xff0c;以满足客户日益增长的需求。近日&#xff0c;浪潮信息再次展现技术实力&…