基于Spring AOP @AspectJ进阶说明

 更新时间:2021年1月20日 22:10  点击:1262

@AspectJ可以使用切点函数定义切点,我们还可以使用逻辑运算符对切点进行复核运算得到复合的切点,为了在切面中重用切点,我们还可以对切点进行命名,以便在其他的地方引用定义过的切点。

当一个连接点匹配多个切点时,需要考虑织入顺序的问题,此外一个重要的问题是如何再增强中访问连接点上下文的信息。

Waiter接口:

package com.yyq.aspectJAdvanced;
public interface Waiter {
 void greetTo(String name);
 void serveTo(String name);
}

NaiveWaiter实现类:

package com.yyq.aspectJAdvanced;
public class NaiveWaiter implements Waiter {
 @Override
 public void greetTo(String name) {
  System.out.println("NaiveWaiter:greet to " + name + "...");
 }
 @Override
 public void serveTo(String name) {
  System.out.println("NaiveWaiter:serving to " + name + "...");
 }
 public void smile(String clientName,int times){
  System.out.println("NaiveWaiter:smile to "+clientName+ times+"times...");
 }
}

NaughtyWaiter实现类:

package com.yyq.aspectJAdvanced;
public class NaughtyWaiter implements Waiter {
 public void greetTo(String clientName) {
  System.out.println("NaughtyWaiter:greet to " + clientName + "...");
 }
 public void serveTo(String clientName) {
  System.out.println("NaughtyWaiter:serving " + clientName + "...");
 }
 public void joke(String clientName, int times) {
  System.out.println("NaughtyWaiter:play " + times + " jokes to " + clientName + "...");
 }
}

Seller接口:

package com.yyq.aspectJAdvanced;
public interface Seller {
 int sell(String goods, String clientName);
}

SmallSeller实现类:

package com.yyq.aspectJAdvanced;
public class SmartSeller implements Seller {
 public int sell(String goods,String clientName) {
  System.out.println("SmartSeller: sell "+goods +" to "+clientName+"...");
  return 100;
 }
 
 public void checkBill(int billId){
  if(billId == 1) throw new IllegalArgumentException("iae Exception");
  else throw new RuntimeException("re Exception");
 }
}

beans.xml配置文件:

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<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-3.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 <aop:aspectj-autoproxy proxy-target-class="true"/>
 <bean id="naiveWaiter" class="com.yyq.aspectJAdvanced.NaiveWaiter"/>
 <bean id="naughtyWaiter" class="com.yyq.aspectJAdvanced.NaughtyWaiter"/>
 <bean id="seller" class="com.yyq.aspectJAdvanced.SmartSeller"/>
 <!--
 <bean class="com.yyq.aspectJAdvanced.TestAspect"/>
 
 <bean class="com.yyq.aspectJAdvanced.TestAspect2"/>
 <bean class="com.yyq.aspectJAdvanced.TestAspect3"/>
 <bean class="com.yyq.aspectJAdvanced.TestAspect4"/>
 <bean class="com.yyq.aspectJAdvanced.TestAspect5"/>
 <bean id="naiveWaiter2" class="com.yyq.aspectJAdvanced.NaiveWaiter2"/>
 <bean class="com.yyq.aspectJAdvanced.TestAspect6"/>
 <bean class="com.yyq.aspectJAdvanced.TestAspect7"/>
 <bean class="com.yyq.aspectJAdvanced.TestAspect8"/>
-->
</beans>

1、切点符合运算

使用切点符合运算符,我们将拥有强大而灵活的切点表达能力。

TestAspect:切点符合运算定义切面

package com.yyq.aspectJAdvanced;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class TestAspect {
 //与非运算
 @Before("!target(com.yyq.aspectJAdvanced.NaiveWaiter) && execution(* serveTo(..))")
 public void notServeInNaiveWaiter(){
  System.out.println("--notServeInNaiveWaiter() executed!--");
 }
 //与运算
 @After("within(com.yyq.aspectJAdvanced.*) && execution(* greetTo(..))")
 public void greetToFun(){
  System.out.println("--greetToFun() executed!--");
 }
 //或运算
 @AfterReturning("target(com.yyq.aspectJAdvanced.Waiter) || target(com.yyq.aspectJAdvanced.Seller)")
 public void waiterOrSeller(){
  System.out.println("--waiterOrSeller() executed!--");
 }
}

测试方法:

@Test
 public void pointAspectJTest() {
  String configPath = "com\\yyq\\aspectJAdvanced\\beans.xml";
  ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
  Waiter naiveWaiter = (Waiter) ctx.getBean("naiveWaiter");
  Waiter naughtyWaiter = (Waiter) ctx.getBean("naughtyWaiter");
  naiveWaiter.greetTo("John");
  naiveWaiter.serveTo("John");
  naughtyWaiter.greetTo("Tom");
  naughtyWaiter.serveTo("Tom");
 }

输出结果:

NaiveWaiter:greet to John...
--greetToFun() executed!--
--waiterOrSeller() executed!--
NaiveWaiter:serving to John...
--waiterOrSeller() executed!--
NaughtyWaiter:greet to Tom...
--greetToFun() executed!--
--waiterOrSeller() executed!--
--notServeInNaiveWaiter() executed!--
NaughtyWaiter:serving Tom...
--waiterOrSeller() executed!--

2、命名切点

切点直接声明在增强方法处被称为匿名切点,匿名切点只能在声明处使用。如果希望在其他地方重用一个切点,我们可以通过@Pointcut注解以及切面类方法对切点进行命名。

TestNamePointcut:命名切点类

package com.yyq.aspectJAdvanced;
import org.aspectj.lang.annotation.Pointcut;
public class TestNamePointcut {
 //通过注解方法inPackage()对该切点进行命名,方法可视域修饰符为private,表明该命名切点只能在本切面类中使用
 @Pointcut("within(com.yyq.aspectJAdvaned.*)")
 private void inPackage(){}
 @Pointcut("execution(* greetTo(..))")
 protected void greetTo(){}
 @Pointcut("inPackage() and greetTo()")
 public void inPkgGreetTo(){}
}

TestAspect2:切面实现类

package com.yyq.aspectJAdvanced;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class TestAspect2 {
 @Before("TestNamePointcut.inPkgGreetTo()")
 public void pkgGreetTo(){
  System.out.println("--pkgGreetTo() executed!--");
 }
 @Before("target(com.yyq.aspectJAdvanced.NaiveWaiter) || TestNamePointcut.inPkgGreetTo()")
 public void pkgGreetToNotnaiveWaiter(){
  System.out.println("--pkgGreetToNotnaiveWaiter() executed!--");
 }
}

测试方法:

@Test
 public void pointAspectJTest2() {
  String configPath = "com\\yyq\\aspectJAdvanced\\beans.xml";
  ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
  NaiveWaiter naiveWaiter = (NaiveWaiter) ctx.getBean("naiveWaiter");
  naiveWaiter.smile("Andy", 2);
 }

输出结果:

--pkgGreetToNotnaiveWaiter() executed!--
NaiveWaiter:smile to Andy2times...

3、增强织入的顺序

一个连接点可以同时匹配多个切点,切点对应的增强在连接点上的织入顺序的安排主要有以下3种情况:

1)如果增强在同一个切面类中声明,则依照增强在切面类中定义的顺序进行织入;

2)如何增强位于不同的切面类中,且这些切面类都实现了org.springframework.core.Order接口,则由接口方法的顺序号决定(顺序号小的先织入);

3)如果增强位于不同的切面类中,且这些切面类没有实现org.springframework.core.Order接口,织入的顺序是不确定的。

4、访问连接点信息

AspectJ使用org.aspectj.lang.JoinPoint接口表示目标类连接点对象,如果是环绕增强时,使用org.aspectj.lang.ProceedingJoinPoint表示连接点对象,该类是JoinPoint的子接口,任何一个增强方法都可以通过将第一个入参声明为JoinPoint访问到连接点上下文的信息。

TestAspect3:切面实现类

@Aspect
public class TestAspect3 {
 @Around("execution(* greetTo(..)) && target(com.yyq.aspectJAdvanced.NaiveWaiter)")
 public void joinPointAccess(ProceedingJoinPoint pjp) throws Throwable {
  System.out.println("---joinPointAccess---");
  System.out.println("args[0]:" + pjp.getArgs()[0]);
  System.out.println("signature:" + pjp.getTarget().getClass());
  pjp.proceed();
  System.out.println("---joinPointAccess---");
 }
}

测试方法:

 @Test
 public void pointAspectJTest3() {
  String configPath = "com\\yyq\\aspectJAdvanced\\beans.xml";
  ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
  Waiter naiveWaiter = (Waiter) ctx.getBean("naiveWaiter");
  naiveWaiter.greetTo("Andy");
 }

输出结果:

---joinPointAccess---
args[0]:Andy
signature:class com.yyq.aspectJAdvanced.NaiveWaiter
NaiveWaiter:greet to Andy...
---joinPointAccess---

5、绑定连接点方法入参

args()用于绑定连接点方法的入参;@annotation()用于绑定连接点方法的注解对象;而@args()用于绑定连接点方法入参的注解。

TestAspect4:切面实现类

@Aspect
public class TestAspect4 {
 @Before("target(com.yyq.aspectJAdvanced.NaiveWaiter) && args(name,num,..)")
 public void bindJoinPointParams(int num, String name) {
  System.out.println("---bindJoinPointParams---");
  System.out.println("name:" + name);
  System.out.println("num:" + num);
  System.out.println("---bindJoinPointParams---");
 }
}

测试方法:

@Test
 public void pointAspectJTest4() {
  String configPath = "com\\yyq\\aspectJAdvanced\\beans.xml";
  ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
  NaiveWaiter naiveWaiter = (NaiveWaiter) ctx.getBean("naiveWaiter");
  naiveWaiter.smile("Andy", 3);
 }

输出结果:

---bindJoinPointParams---
name:Andy
num:3
---bindJoinPointParams---
NaiveWaiter:smile to Andy 3 times...

6、绑定代理对象

使用this()或target()可绑定被代理对象实例,在通过类实例名绑定对象时,还依然具有原来连接点匹配的功能,只不过类名是通过增强方法中同名入参的类型间接决定罢了。

TestAspect5:切面实现类

@Aspect
public class TestAspect5 {
 @Before("this(waiter)")
 public void bindProxyObj(Waiter waiter){
  System.out.println("---bindProxyObj---");
  System.out.println(waiter.getClass().getName());
  System.out.println("---bindProxyObj---");
 }
}

测试方法:

@Test
 public void pointAspectJTest5() {
  String configPath = "com\\yyq\\aspectJAdvanced\\beans.xml";
  ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
  Waiter waiter = (Waiter) ctx.getBean("naiveWaiter");
  waiter.greetTo("Yang");
 }

输出结果:

---bindProxyObj---
com.yyq.aspectJAdvanced.NaiveWaiter$$EnhancerByCGLIB$$fefafe52
---bindProxyObj---
NaiveWaiter:greet to Yang...

7、绑定类注解对象

@within()和@target()函数可以将目标类的注解对象绑定到增强方法中,我们通过@within()演示注解绑定的操作。

TestAspect6:切面测试类

@Aspect
public class TestAspect6 {
 @Before("@within(m)")
 public void bindTypeAnnoObject(Monitorable m) {
  System.out.println("---bindTypeAnnoObject---");
  System.out.println(m.getClass().getName());
  System.out.println("---bindTypeAnnoObject---");
 }
}

测试方法:

@Test
 public void pointAspectJTest6() {
  String configPath = "com\\yyq\\aspectJAdvanced\\beans.xml";
  ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
  Waiter waiter = (Waiter) ctx.getBean("naiveWaiter2");
  ((NaiveWaiter2)waiter).greetTo("Yang");
 }

输出结果:

---bindTypeAnnoObject---
$Proxy4
---bindTypeAnnoObject---
NaiveWaiter:greet to Yang...

8、绑定返回值

在后置增强中,我们可以通过returning绑定连接点方法的返回值。

TestAspect7:切面实现类

@Aspect
public class TestAspect7 {
 @AfterReturning(value = "target(com.yyq.aspectJAdvanced.SmartSeller)", returning = "retVal")
 public void bindReturnValue(int retVal) {
  System.out.println("---bindReturnValue---");
  System.out.println("returnValue:" + retVal);
  System.out.println("---bindReturnValue---");
 }
}

测试方法:

 @Test
 public void pointAspectJTest7() {
  String configPath = "com\\yyq\\aspectJAdvanced\\beans.xml";
  ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
  SmartSeller seller = (SmartSeller) ctx.getBean("seller");
  seller.sell("Beer", "John");
 }

输出结果:

SmartSeller: sell Beer to John...
---bindReturnValue---
returnValue:100
---bindReturnValue---

9、绑定抛出的异常

和通过切点函数绑定连接点信息不同,连接点抛出的异常必须使用AfterThrowing注解的throwing成员进行绑定。

TestAspect8:切面实现类

@Aspect
public class TestAspect8 {
 @AfterThrowing(value = "target(com.yyq.aspectJAdvanced.SmartSeller)", throwing = "iae")
 public void bindException(IllegalArgumentException iae) {
  System.out.println("---bindException---");
  System.out.println("exception:" + iae.getMessage());
  System.out.println("---bindException---");
 }
}

测试方法:

 @Test
 public void pointAspectJTest8() {
  String configPath = "com\\yyq\\aspectJAdvanced\\beans.xml";
  ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
  SmartSeller seller = (SmartSeller) ctx.getBean("seller");
  seller.checkBill(1);
 }

输出结果:

---bindException---
exception:iae Exception
---bindException---

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。如有错误或未考虑完全的地方,望不吝赐教。

[!--infotagslink--]

相关文章

  • Spring AOP 对象内部方法间的嵌套调用方式

    这篇文章主要介绍了Spring AOP 对象内部方法间的嵌套调用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-08-29
  • Spring Cloud 中@FeignClient注解中的contextId属性详解

    这篇文章主要介绍了Spring Cloud 中@FeignClient注解中的contextId属性详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-25
  • Springboot如何实现Web系统License授权认证

    这篇文章主要介绍了Springboot如何实现Web系统License授权认证,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-05-28
  • 如何在Spring WebFlux的任何地方获取Request对象

    这篇文章主要介绍了如何在Spring WebFlux的任何地方获取Request对象,帮助大家更好的理解和使用springboot框架,感兴趣的朋友可以了解下...2021-01-26
  • 详解SpringCloudGateway内存泄漏问题

    这篇文章主要介绍了详解SpringCloudGateway内存泄漏问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-07-16
  • Spring为什么不推荐使用@Autowired注解详析

    @Autowired 注解的主要功能就是完成自动注入,使用也非常简单,但这篇文章主要给大家介绍了关于Spring为什么不推荐使用@Autowired注解的相关资料,需要的朋友可以参考下...2021-11-03
  • Springboot如何使用mybatis实现拦截SQL分页

    这篇文章主要介绍了Springboot使用mybatis实现拦截SQL分页,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-19
  • SpringMVC文件上传原理及实现过程解析

    这篇文章主要介绍了SpringMVC文件上传原理及实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-07-15
  • Spring Data JPA 关键字Exists的用法说明

    这篇文章主要介绍了Spring Data JPA 关键字Exists的用法说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-06-10
  • tomcat启动完成执行 某个方法 定时任务(Spring)操作

    这篇文章主要介绍了tomcat启动完成执行 某个方法 定时任务(Spring)操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-25
  • 使用Maven 搭建 Spring MVC 本地部署Tomcat的详细教程

    这篇文章主要介绍了使用Maven 搭建 Spring MVC 本地部署Tomcat,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-08-16
  • Java Spring Cloud 负载均衡详解

    这篇文章主要介绍了Spring Cloud负载均衡及远程调用实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2021-09-18
  • SpringMvc自动装箱及GET请求参数原理解析

    这篇文章主要介绍了SpringMvc自动装箱及GET请求参数原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-09-19
  • SpringMvc获取请求头请求体消息过程解析

    这篇文章主要介绍了SpringMvc获取请求头请求体消息过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-09-17
  • Springboot使用thymeleaf动态模板实现刷新

    这篇文章主要介绍了Springboot使用thymeleaf动态模板实现刷新,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-08-31
  • Idea打包springboot项目没有.original文件解决方案

    这篇文章主要介绍了Idea打包springboot项目没有.original文件解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-07-26
  • spring boot 使用utf8mb4的操作

    这篇文章主要介绍了spring boot 使用utf8mb4的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-20
  • Springmvc ResponseBody响应json数据实现过程

    这篇文章主要介绍了Springmvc ResponseBody响应json数据实现过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-10-26
  • SpringData Repository接口用法解析

    这篇文章主要介绍了SpringData Repository接口用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-08-27
  • Spring boot 无法注入service问题

    这篇文章主要介绍了Spring boot 无法注入service问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-10-09