Spring AOP--注解代理、静态代理、动态代理、cglib代理、多切面顺序控制

2024-02-21 00:32

本文主要是介绍Spring AOP--注解代理、静态代理、动态代理、cglib代理、多切面顺序控制,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

代理:通过代理对象访问目标对象,这样可以在目标对象实现的基础上,增强额外的功能操作(即扩展目标对象的功能)。

简言之,在调用目标对象的方法前后做一些操作,以达到增强的目的。

注意:类内部自调用不会触发AOP。

 

注解代理实现:

注解类:

package com.xxx.annotations;import java.lang.annotation.*;@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface User {
}

AOP:

package com.xxx.aspects;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;@Aspect
@Component
public class AuthorityAspect {@Around("@annotation(user)")private <T> T user(ProceedingJoinPoint joinPoint, User user) throws Throwable {/*** 方法执行前相关操作**/T proceed = (T) joinPoint.proceed();/*** 方法执行后相关操作**/return proceed;}}

静态代理、动态代理、cglib代理、多切面顺序控制:

动物类接口:

public interface Animal {void call();
}

小狗类

public class Dog implements Animal {@Overridepublic void call() {System.out.println("汪汪");}
}

小猫类

public class Cat implements Animal {@Overridepublic void call() {System.out.println("喵喵");}
}

 

静态代理

 

动物代理类

public class AnimalProxy implements Animal {private Animal animal;public AnimalProxy(Animal animal){this.animal=animal;}@Overridepublic void call() {System.out.println("就像");animal.call();System.out.println("一只"+this.animal.getClass().getSimpleName()+"一样");}
}

测试类:

public class TestProxy {//静态代理@Testpublic void testStaticProxy(){Dog dog=new Dog();AnimalProxy animalProxy=new AnimalProxy(dog);animalProxy.call();}
}

 

动态代理

 

动态动物代理类

public class DynamicAnimalProxy implements InvocationHandler {private Animal animal;public DynamicAnimalProxy(Animal animal){this.animal=animal;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("就像");method.invoke(animal,args);System.out.println("一样");return null;}
}

测试类

public class TestProxy {//静态代理@Testpublic void testStaticProxy() {Dog dog = new Dog();AnimalProxy animalProxy = new AnimalProxy(dog);animalProxy.call();}@Testpublic void testDynamicProxy() {Cat cat = new Cat();DynamicAnimalProxy dynamicAnimalProxy = new DynamicAnimalProxy(cat);ClassLoader classLoader = cat.getClass().getClassLoader();Animal animal = (Animal) Proxy.newProxyInstance(classLoader, cat.getClass().getInterfaces(), dynamicAnimalProxy);animal.call();}
}

 

cglib代理

 

注解方式:

@RestController
public class DogController {@Resourceprivate Animal dog;@RequestMapping(value = "/dogCall",method = RequestMethod.GET)public JsonData dogCall(String name){dog.call();return JsonData.success();}
}

@Aspect
@Component("myAspect")
public class MyAspect {// * 表示任意返回类型  (..) 表示匹配任意参数@Pointcut("execution(* com.sunshine.shine.Service.impl.Dog.call(..))")public void pointCut(){}@Before("pointCut()")public void before(){System.out.println("before------");}@Around("pointCut()")public void around(ProceedingJoinPoint joinPoint) throws Throwable{System.out.println("around before------");joinPoint.proceed(); //执行被加强的方法System.out.println("around after------");}@After("pointCut()")public void after(){System.out.println("after-------");}@AfterReturning("pointCut()")public void afterReturning(){System.out.println("afterReturn-----");}@AfterThrowing("pointCut()")public void afterThrowing(){System.out.println("afterThrowing----");}}

运行程序,请求 /dogCall,结果如下

around before------
before------
汪汪
around after------
after-------
afterReturn-----

XML配置文件方式:

 <bean id="aspectXml" class="com.sunshine.shine.Proxys.MyAspectXml" /><aop:aspectj-autoproxy proxy-target-class="true" /><aop:config><aop:aspect id="aspect" ref="aspectXml"><aop:pointcut expression="execution(* com.sunshine.shine.Service.impl.Dog.call(..))" id="refcall" /><aop:before method="before" pointcut-ref="refcall" /><aop:after-returning method="afterReturning" pointcut-ref="refcall" /><aop:after-throwing method="afterThrowing" pointcut-ref="refcall" /><aop:around method="around" pointcut-ref="refcall" /><aop:after method="after" pointcut-ref="refcall"/></aop:aspect></aop:config>

public class MyAspectXml {public void before(){System.out.println("before------");}public void around(ProceedingJoinPoint joinPoint) throws Throwable{System.out.println("around before------");joinPoint.proceed();//执行被加强的方法System.out.println("around after------");}public void after(){System.out.println("after-------");}public void afterReturning(){System.out.println("afterReturn-----");}public void afterThrowing(){System.out.println("afterThrowing----");}}

运行程序,请求 /dogCall,结果如下

before------
around before------
汪汪
after-------
around after------
afterReturn-----

 

总结:

注解方式执行顺序:

around beforebefore执行方法around afterafterafterReturning

XML文件配置方式执行顺序:

beforearound before执行方法afteraround afterafterReturning

 

多切面顺序控制

 

原切面加个顺序  @Order(1)


@Order(1)
@Aspect
@Component("myAspect")
public class MyAspect {//    @DeclareParents(value = "com.sunshine.shine.Service.impl.Dog+",defaultImpl = AnimalServiceImpl.class)
//    public AnimalService animalService;@Pointcut("execution(* com.sunshine.shine.Service.impl.Dog.call(..))")public void pointCut(){}@Before("pointCut()")public void before(){System.out.println("before------");}@Around("pointCut()")public void around(ProceedingJoinPoint joinPoint) throws Throwable{System.out.println("around before------");joinPoint.proceed();System.out.println("around after------");}@After("pointCut()")public void after(){System.out.println("after-------");}@AfterReturning("pointCut()")public void afterReturning(){System.out.println("afterReturn-----");}@AfterThrowing("pointCut()")public void afterThrowing(){System.out.println("afterThrowing----");}}

再添加两个相同的切面  

@Aspect
@Component
public class MyAspect2 implements Ordered {//    @DeclareParents(value = "com.sunshine.shine.Service.impl.Dog+",defaultImpl = AnimalServiceImpl.class)
//    public AnimalService animalService;@Pointcut("execution(* com.sunshine.shine.Service.impl.Dog.call(..))")public void pointCut(){}@Before("pointCut()")public void before(){System.out.println("2before------");}@Around("pointCut()")public void around(ProceedingJoinPoint joinPoint) throws Throwable{System.out.println("2around before------");joinPoint.proceed();System.out.println("2around after------");}@After("pointCut()")public void after(){System.out.println("2after-------");}@AfterReturning("pointCut()")public void afterReturning(){System.out.println("2afterReturn-----");}@AfterThrowing("pointCut()")public void afterThrowing(){System.out.println("2afterThrowing----");}@Overridepublic int getOrder() {return -1;}
}
@Order(0)
@Aspect
@Component
public class MyAspect3 {//    @DeclareParents(value = "com.sunshine.shine.Service.impl.Dog+",defaultImpl = AnimalServiceImpl.class)
//    public AnimalService animalService;@Pointcut("execution(* com.sunshine.shine.Service.impl.Dog.call(..))")public void pointCut(){}@Before("pointCut()")public void before(){System.out.println("3before------");}@Around("pointCut()")public void around(ProceedingJoinPoint joinPoint) throws Throwable{System.out.println("3around before------");joinPoint.proceed();System.out.println("3around after------");}@After("pointCut()")public void after(){System.out.println("3after-------");}@AfterReturning("pointCut()")public void afterReturning(){System.out.println("3afterReturn-----");}@AfterThrowing("pointCut()")public void afterThrowing(){System.out.println("3afterThrowing----");}}

运行结果(类似责任链):

2around before------
2before------
3around before------
3before------
around before------
before------
汪汪
around after------
after-------
afterReturn-----
3around after------
3after-------
3afterReturn-----
2around after------
2after-------
2afterReturn-----

 

运用了两种实现控制顺序方式:

1、@Order

2、implement Ordered

    @Overridepublic int getOrder() {return -1;}

 

MyAspect  Order值为  1
MyAspect2 Order值为  -1
MyAspect3 Order值为 0

-1<0<1

所以顺序为  2 -> 3 -> 1

 

这篇关于Spring AOP--注解代理、静态代理、动态代理、cglib代理、多切面顺序控制的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

一文详解如何在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.