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

相关文章

python使用Akshare与Streamlit实现股票估值分析教程(图文代码)

《python使用Akshare与Streamlit实现股票估值分析教程(图文代码)》入职测试中的一道题,要求:从Akshare下载某一个股票近十年的财务报表包括,资产负债表,利润表,现金流量表,保存... 目录一、前言二、核心知识点梳理1、Akshare数据获取2、Pandas数据处理3、Matplotl

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.