栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

ProxyBean的实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ProxyBean的实现

如何将服务类和拦截方法置入对应的流程是ProxyBean要实现的功能。首先要理解动态代理模式。其实代理很简单,例如当你需要采访一名儿童时,首先需要经过他父母的同意,在一些问题上父母也许替他回答,而对于另一些问题,也许父母觉得不太合适,这个小孩会拒绝掉,显然这是父母就是证明儿童的代理(proxy)了。通过代理可以增强或者控制对儿童这个真实对象(target)的访问。
在JDK中提供了类proxy的静态方法——newProxyInstance

public static Object newProxyInstance(ClassLoader classLoader, Class[] interfaces, InvocationHandler invocationHandker) throw IllegalArgumentException
  • classLoader——类加载器
  • interfaces——绑定的接口,也就是把代理对象绑定到哪些接口下,可以是多个
  • invocationHandler——绑定代理对象逻辑实现
    这里的invocationHandler是一个接口InvocationHandler对象,它定义了一个invoke方法,这个方法就是实现代理对象的逻辑的。
package com.springboot.chapter4.proxy;
import com.springboot.chapter4.intercept.Interceptor;import com.springboot.chapter4.invoke.Invocation;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class ProxyBean implements InvocationHandler {    private Object target = null;    private Interceptor interceptor = null;        public static Object getProxyBean(Object target, Interceptor interceptor) {        ProxyBean proxyBean = new ProxyBean();        //保存代理对象        proxyBean.target = target;        //保存拦截器        proxyBean.interceptor = interceptor;        //生成代理对象        Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(),                target.getClass().getInterfaces(), proxyBean);        return proxy;    }    /**     * 处理代理对象
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/692867.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号