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

相关文章

Spring Security+JWT如何实现前后端分离权限控制

《SpringSecurity+JWT如何实现前后端分离权限控制》本篇将手把手教你用SpringSecurity+JWT搭建一套完整的登录认证与权限控制体系,具有很好的参考价值,希望对大家... 目录Spring Security+JWT实现前后端分离权限控制实战一、为什么要用 JWT?二、JWT 基本结构

java解析jwt中的payload的用法

《java解析jwt中的payload的用法》:本文主要介绍java解析jwt中的payload的用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解析jwt中的payload1. 使用 jjwt 库步骤 1:添加依赖步骤 2:解析 JWT2. 使用 N

springboot项目如何开启https服务

《springboot项目如何开启https服务》:本文主要介绍springboot项目如何开启https服务方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录springboot项目开启https服务1. 生成SSL证书密钥库使用keytool生成自签名证书将

Java实现优雅日期处理的方案详解

《Java实现优雅日期处理的方案详解》在我们的日常工作中,需要经常处理各种格式,各种类似的的日期或者时间,下面我们就来看看如何使用java处理这样的日期问题吧,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言一、日期的坑1.1 日期格式化陷阱1.2 时区转换二、优雅方案的进阶之路2.1 线程安全重构2

Java中的JSONObject详解

《Java中的JSONObject详解》:本文主要介绍Java中的JSONObject详解,需要的朋友可以参考下... Java中的jsONObject详解一、引言在Java开发中,处理JSON数据是一种常见的需求。JSONObject是处理JSON对象的一个非常有用的类,它提供了一系列的API来操作J

SpringBoot多数据源配置完整指南

《SpringBoot多数据源配置完整指南》在复杂的企业应用中,经常需要连接多个数据库,SpringBoot提供了灵活的多数据源配置方式,以下是详细的实现方案,需要的朋友可以参考下... 目录一、基础多数据源配置1. 添加依赖2. 配置多个数据源3. 配置数据源Bean二、JPA多数据源配置1. 配置主数据

将Java程序打包成EXE文件的实现方式

《将Java程序打包成EXE文件的实现方式》:本文主要介绍将Java程序打包成EXE文件的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录如何将Java程序编程打包成EXE文件1.准备Java程序2.生成JAR包3.选择并安装打包工具4.配置Launch4

SpringBoot内嵌Tomcat临时目录问题及解决

《SpringBoot内嵌Tomcat临时目录问题及解决》:本文主要介绍SpringBoot内嵌Tomcat临时目录问题及解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录SprinjavascriptgBoot内嵌Tomcat临时目录问题1.背景2.方案3.代码中配置t

SpringBoot使用GZIP压缩反回数据问题

《SpringBoot使用GZIP压缩反回数据问题》:本文主要介绍SpringBoot使用GZIP压缩反回数据问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录SpringBoot使用GZIP压缩反回数据1、初识gzip2、gzip是什么,可以干什么?3、Spr

Java程序进程起来了但是不打印日志的原因分析

《Java程序进程起来了但是不打印日志的原因分析》:本文主要介绍Java程序进程起来了但是不打印日志的原因分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java程序进程起来了但是不打印日志的原因1、日志配置问题2、日志文件权限问题3、日志文件路径问题4、程序