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

相关文章

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.

idea maven编译报错Java heap space的解决方法

《ideamaven编译报错Javaheapspace的解决方法》这篇文章主要为大家详细介绍了ideamaven编译报错Javaheapspace的相关解决方法,文中的示例代码讲解详细,感兴趣的... 目录1.增加 Maven 编译的堆内存2. 增加 IntelliJ IDEA 的堆内存3. 优化 Mave

Java String字符串的常用使用方法

《JavaString字符串的常用使用方法》String是JDK提供的一个类,是引用类型,并不是基本的数据类型,String用于字符串操作,在之前学习c语言的时候,对于一些字符串,会初始化字符数组表... 目录一、什么是String二、如何定义一个String1. 用双引号定义2. 通过构造函数定义三、St

springboot filter实现请求响应全链路拦截

《springbootfilter实现请求响应全链路拦截》这篇文章主要为大家详细介绍了SpringBoot如何结合Filter同时拦截请求和响应,从而实现​​日志采集自动化,感兴趣的小伙伴可以跟随小... 目录一、为什么你需要这个过滤器?​​​二、核心实现:一个Filter搞定双向数据流​​​​三、完整代码

SpringBoot利用@Validated注解优雅实现参数校验

《SpringBoot利用@Validated注解优雅实现参数校验》在开发Web应用时,用户输入的合法性校验是保障系统稳定性的基础,​SpringBoot的@Validated注解提供了一种更优雅的解... 目录​一、为什么需要参数校验二、Validated 的核心用法​1. 基础校验2. php分组校验3

Java Predicate接口定义详解

《JavaPredicate接口定义详解》Predicate是Java中的一个函数式接口,它代表一个判断逻辑,接收一个输入参数,返回一个布尔值,:本文主要介绍JavaPredicate接口的定义... 目录Java Predicate接口Java lamda表达式 Predicate<T>、BiFuncti

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

Spring Security方法级安全控制@PreAuthorize注解的灵活运用小结

《SpringSecurity方法级安全控制@PreAuthorize注解的灵活运用小结》本文将带着大家讲解@PreAuthorize注解的核心原理、SpEL表达式机制,并通过的示例代码演示如... 目录1. 前言2. @PreAuthorize 注解简介3. @PreAuthorize 核心原理解析拦截与