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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

第10章 中断和动态时钟显示

第10章 中断和动态时钟显示 从本章开始,按照书籍的划分,第10章开始就进入保护模式(Protected Mode)部分了,感觉从这里开始难度突然就增加了。 书中介绍了为什么有中断(Interrupt)的设计,中断的几种方式:外部硬件中断、内部中断和软中断。通过中断做了一个会走的时钟和屏幕上输入字符的程序。 我自己理解中断的一些作用: 为了更好的利用处理器的性能。协同快速和慢速设备一起工作

高效+灵活,万博智云全球发布AWS无代理跨云容灾方案!

摘要 近日,万博智云推出了基于AWS的无代理跨云容灾解决方案,并与拉丁美洲,中东,亚洲的合作伙伴面向全球开展了联合发布。这一方案以AWS应用环境为基础,将HyperBDR平台的高效、灵活和成本效益优势与无代理功能相结合,为全球企业带来实现了更便捷、经济的数据保护。 一、全球联合发布 9月2日,万博智云CEO Michael Wong在线上平台发布AWS无代理跨云容灾解决方案的阐述视频,介绍了