Spring(十)通过动态代理(JDK的Proxy)和cglib实现AOP技术

2024-06-16 11:08

本文主要是介绍Spring(十)通过动态代理(JDK的Proxy)和cglib实现AOP技术,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目标对象的所有接口方法

package test.spring.service;public interface PersonService {public String getPersonName(Integer id);public void save(String name);}

目标对象

package test.spring.service.impl;import test.spring.service.PersonService;//代理对象实现目标对象所有接口
public class PersonServiceBean implements PersonService {private String user = null;public PersonServiceBean() {}public PersonServiceBean(String user) {super();this.user = user;}public String getUser() {return user;}public void setUser(String user) {this.user = user;}@Overridepublic String getPersonName(Integer id) {// TODO Auto-generated method stubreturn "getPersonName";}@Overridepublic void save(String name) {// TODO Auto-generated method stubSystem.out.println("save()->>" + name);}}

代理对象,拦截所有业务方法,根据user是否为null判断用户是否有权限,有权限就允许执行业务方法,无权限就不执行。

package test.spring.aop;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;import test.spring.service.impl.PersonServiceBean;public class ProxyFactory implements InvocationHandler {private Object proxyObject;// 创建代理对象实例public Object createProxyIntance(Object proxyObject) {this.proxyObject = proxyObject;/** 第一个参数:类装载器 * 第二个参数:取得目标对象的接口,Proxy会将这些接口全部实现 * 第三个参数:一个回调函数,确定实现哪个类的接口*/return Proxy.newProxyInstance(this.proxyObject.getClass().getClassLoader(), this.proxyObject.getClass().getInterfaces(),this);}/** 第一个参数:代理对象 * 第二个参数:被拦截到的方法 * 第三个参数:方法的输入参数*/@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {PersonServiceBean personServiceBean = (PersonServiceBean) this.proxyObject;Object target = null;// user不为空说明有权限if (personServiceBean.getUser() != null) {// 把对代理对象方法的调用委派给目标对象target = method.invoke(proxyObject, args);}return target;}
}

权限测试

package test.spring.junit;import static org.junit.Assert.*;import org.junit.Test;import test.spring.aop.ProxyFactory;
import test.spring.service.PersonService;
import test.spring.service.impl.PersonServiceBean;public class AOPTest {@Testpublic void test() {ProxyFactory pFactory = new ProxyFactory();// PersonService pService=(PersonService)// pFactory.createProxyIntance(new PersonServiceBean("kkk"));// 改为默认函数pService.save("ppp")就执行不了,因为前面的user=null,相当于没有权限执行PersonService pService = (PersonService) pFactory.createProxyIntance(new PersonServiceBean());pService.save("ppp");}}


以上适用于目标对象实现了接口的情况,如果目标对象没有接口,就会选择用Cglib

首先导入cglib-nodep-2.1_3.jar

package test.spring.service.impl;//代理对象实现目标对象所有接口
public class PersonServiceBean2 {private String user = null;public PersonServiceBean2() {}public PersonServiceBean2(String user) {super();this.user = user;}public String getUser() {return user;}public void setUser(String user) {this.user = user;}public void save(String name) {// TODO Auto-generated method stubSystem.out.println("save()->>" + name);}}

package test.spring.aop;import java.lang.reflect.Method;import test.spring.service.impl.PersonServiceBean2;import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;//目标对象没有接口
public class CglibProxyFactory implements MethodInterceptor {private Object proxyObject;// 创建代理对象实例public Object createProxyIntance(Object proxyObject) {this.proxyObject = proxyObject;Enhancer enhancer = new Enhancer();/** 需设置父类,即目标类。创建的对象继承目标类,对目标类中* 所有非final的所有方法进行覆盖,然后在覆盖的代码里面* 添加一些自身的代码*/enhancer.setSuperclass(this.proxyObject.getClass());enhancer.setCallback((Callback) this);return enhancer.create();}/** 第一个参数:代理对象本身 * 第二个参数:被拦截到的方法 * 第三个参数:方法的参数 * 第四个参数:方法的代理对象*/// 当代理对象的业务方法被回调的时候会调用这个方法@Overridepublic Object intercept(Object proxy, Method method, Object[] args,MethodProxy methodProxy) throws Throwable {PersonServiceBean2 personServiceBean = (PersonServiceBean2) this.proxyObject;Object target = null;// user不为空说明有权限if (personServiceBean.getUser() != null) {// 把对方法的调用委派给目标对象target = methodProxy.invoke(proxyObject, args);}return target;}
}

package test.spring.junit;import static org.junit.Assert.*;import org.junit.Test;import test.spring.aop.CglibProxyFactory;
import test.spring.aop.ProxyFactory;
import test.spring.service.PersonService;
import test.spring.service.impl.PersonServiceBean;
import test.spring.service.impl.PersonServiceBean2;public class AOPTest2 {@Testpublic void test() {CglibProxyFactory pFactory = new CglibProxyFactory();// 此时PersonServiceBean没有接口PersonServiceBean2 pService = (PersonServiceBean2) pFactory.createProxyIntance(new PersonServiceBean2("kkk"));pService.save("ppp");}}


这篇关于Spring(十)通过动态代理(JDK的Proxy)和cglib实现AOP技术的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

Spring @Scheduled注解及工作原理

《Spring@Scheduled注解及工作原理》Spring的@Scheduled注解用于标记定时任务,无需额外库,需配置@EnableScheduling,设置fixedRate、fixedDe... 目录1.@Scheduled注解定义2.配置 @Scheduled2.1 开启定时任务支持2.2 创建

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

Conda虚拟环境的复制和迁移的四种方法实现

《Conda虚拟环境的复制和迁移的四种方法实现》本文主要介绍了Conda虚拟环境的复制和迁移的四种方法实现,包括requirements.txt,environment.yml,conda-pack,... 目录在本机复制Conda虚拟环境相同操作系统之间复制环境方法一:requirements.txt方法

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1