Spring AOP基于@AspectJ注解的切面

2024-03-13 17:20

本文主要是介绍Spring AOP基于@AspectJ注解的切面,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

该篇博客讲述基于AspectJ的注解方式实现AOP切面,关于AOP的一些概念性问题可以转战https://blog.csdn.net/w_linux/article/details/80194768

该篇博客主要阐述

1、编写切点(@Pointcut)
2、基于AspectJ的注解方式实现日志打印
3、环绕通知用法
4、JoinPoint用法

一、编写切点(@Pointcut)

@Pointcut需要在切面中使用,如下

这里写图片描述

Pointcut定义时,还可以使用&&、||、! 这三个运算

这里写图片描述

编写切点表达式

这里写图片描述

AspectJ指示器

当我们查看这些Spring支持的指示器时,注意只有execution指示器是唯一的执行匹配,而其他的指示器都是用于限制匹配的。这说明execution指示器是我们在编写切点定义时最主要使用的指示器

这里写图片描述


二、基于AspectJ的注解方式实现日志打印

1、场景分析

在一个经典的业务逻辑(加减乘除)中需要每次执行某个方法时,打印一些增强该业务逻辑的功能,比如某个方法执行完毕后提示用户执行完毕等日志功能

2、解决方案

使用基于@AspectJ的注解方式来实现日志打印,既不用在核心业务方法中添加一些非核心代码,又能实现自己想要实现的功能,利用前置通知、后置通知、返回通知、异常通知实现

前提:使用AspectJ注解需要依赖于以下几个类库
  • aspectjweaver-1.6.10.jar
  • spring-aop-4.3.10.RELEASE.jar
  • spring-aspects-4.3.10.RELEASE.jar

当然最省力的办法就是将所有Spring的jar都加到classpath中

3、代码

Arithmetic.java(核心业务代码)

package com.linjie.aop;import org.springframework.stereotype.Component;
/**
* @author LinJie E-mail:ash-ali@163.com
* @version 创建时间:2018年5月6日 下午7:53:56
* @核心业务:基本运算
*/
@Component("arithmetic")
public class Arithmetic {//addpublic int add(int d,int e) {System.out.println("add method END!");System.out.println();return d+e;}//subtractionpublic int sub(int a,int b) {System.out.println("sub method END!");System.out.println();return a-b;}//multiplicativepublic int mul(int a,int b) {System.out.println("mul method END!");System.out.println();return a*b;}//divisionpublic int div(int a,int b) {System.out.println("div method END!");System.out.println();return a/b;}
}

LogginAspectJ.java(基于AspectJ的注解方式的切面——日志)

package com.linjie.aop;import java.util.Arrays;import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;/*** @author LinJie* log功能,不影响核心业务*/
@Component("logginAspectJ")
@Aspect
public class LogginAspectJ {/**定义一个方法,用于声明切点表达式,该方法一般没有方法体*@Pointcut用来声明切点表达式*通知直接使用定义的方法名即可引入当前的切点表达式 */@Pointcut("execution(* com.linjie.aop.Arithmetic.*(..))")public void PointcutDeclaration() {}//前置通知,方法执行之前执行@Before("PointcutDeclaration()")public void BeforeMethod(JoinPoint jp) {    String methodName = jp.getSignature().getName();Object[] args = jp.getArgs();System.out.println("BeforeMethod  The method   "+ methodName +"   parameter is  "+ Arrays.asList(args));System.out.println("add before");System.out.println();}//后置通知,方法执行之后执行(不管是否发生异常)@After("PointcutDeclaration()")public void AfterMethod(JoinPoint jp) {String methodName = jp.getSignature().getName();Object[] args = jp.getArgs();System.out.println("AfterMethod  The method    "+ methodName +"   parameter is  "+Arrays.asList(args));System.out.println();}//返回通知,方法正常执行完毕之后执行@AfterReturning(value="PointcutDeclaration()",returning="result")public void AfterReturningMethod(JoinPoint jp,Object result) {String methodName = jp.getSignature().getName();Object[] args = jp.getArgs();System.out.println("AfterReturningMethod  The method   "+ methodName +"   parameter is  "+Arrays.asList(args)+" "+result);System.out.println();} //异常通知,在方法抛出异常之后执行@AfterThrowing(value="PointcutDeclaration()",throwing="e")public void AfterThrowingMethod(JoinPoint jp,Exception e) {String methodName = jp.getSignature().getName();System.out.println("AfterThrowingMethod  The method   "+ methodName +"exception :"+e);}
}

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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><!-- 扫描 --><context:component-scan base-package="com.linjie.aop"></context:component-scan>  <!-- 使AspectJ注解自动为匹配的类生成代理对象 --><aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>

在Spring IoC容器中启动AspectJ注解支持,只要在Bean的配置文件中定义一个空的XML元素

 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

测试类

package com.linjie.aop;import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** @author LinJie* 测试*/
public class SpringTest {@Testpublic void test() {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");Arithmetic arithmetic = (Arithmetic) context.getBean("arithmetic");int result = arithmetic.add(1, 2);System.out.println("result: "+result);System.out.println("--------------");result = arithmetic.div(8, 1);System.out.println("result: "+result);}
}

运行结果

这里写图片描述


三、环绕通知用法

环绕通知是最为强大的通知,这里与以上的切面不同以外其他都相同

这里写图片描述


四、JoinPoint用法

可以在上面的切面代码中发现参数JoinPoint,下面就阐述下该参数的用法

JoinPoint对象封装了SpringAop中切面方法的信息,在切面方法中添加JoinPoint参数,就可以获取到封装了该方法信息的JoinPoint对象.

常用方法

这里写图片描述

ProceedingJoinPoint对象

ProceedingJoinPoint对象是JoinPoint的子接口,该对象用在@Around的切面方法中,常用有以下两个方法

这里写图片描述


参考

《Spring IN ACTION》

这篇关于Spring AOP基于@AspectJ注解的切面的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/805601

相关文章

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

mapstruct中的@Mapper注解的基本用法

《mapstruct中的@Mapper注解的基本用法》在MapStruct中,@Mapper注解是核心注解之一,用于标记一个接口或抽象类为MapStruct的映射器(Mapper),本文给大家介绍ma... 目录1. 基本用法2. 常用属性3. 高级用法4. 注意事项5. 总结6. 编译异常处理在MapSt

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

java中long的一些常见用法

《java中long的一些常见用法》在Java中,long是一种基本数据类型,用于表示长整型数值,接下来通过本文给大家介绍java中long的一些常见用法,感兴趣的朋友一起看看吧... 在Java中,long是一种基本数据类型,用于表示长整型数值。它的取值范围比int更大,从-922337203685477

java Long 与long之间的转换流程

《javaLong与long之间的转换流程》Long类提供了一些方法,用于在long和其他数据类型(如String)之间进行转换,本文将详细介绍如何在Java中实现Long和long之间的转换,感... 目录概述流程步骤1:将long转换为Long对象步骤2:将Longhttp://www.cppcns.c

SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程

《SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程》LiteFlow是一款专注于逻辑驱动流程编排的轻量级框架,它以组件化方式快速构建和执行业务流程,有效解耦复杂业务逻辑,下面给大... 目录一、基础概念1.1 组件(Component)1.2 规则(Rule)1.3 上下文(Conte

SpringBoot服务获取Pod当前IP的两种方案

《SpringBoot服务获取Pod当前IP的两种方案》在Kubernetes集群中,SpringBoot服务获取Pod当前IP的方案主要有两种,通过环境变量注入或通过Java代码动态获取网络接口IP... 目录方案一:通过 Kubernetes Downward API 注入环境变量原理步骤方案二:通过