• aop技术


    粗粒度,细粒度

    使用代理

    客户端------>代理对象----->目标对象

    代理放行了,就调用目标对象的方法

    静态代理(很少用),动态代理

    为目标对象创建动态代理对象,Proxy类,jdk提供

    InvocationHandler其实是回调

    public class JDKProxyFactory implements InvocationHandler {
        private Object targetObject;
        public Object createProxyInstance(Object targetObject){
            this.targetObject=targetObject;
            //生成的动态代理实例要实现目标代理的所有接口
            return Proxy.newProxyInstance(
                    this.targetObject.getClass().getClassLoader(),
                    this.targetObject.getClass().getInterfaces(),this);
            
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            // TODO Auto-generated method stub
            System.out.println("begin invoking....");
            PersonServiceBean personService=(PersonServiceBean)this.targetObject;
            Object result=null;
            if(personService.getUser()!=null){
                result=method.invoke(targetObject, args);
            }else{
                System.out.println("你没有权限");
            }
            System.out.println("end invoking....");
            
            return result;
        }
    }

    测试代码

    @Test
        public void proxyTest(){
            JDKProxyFactory factory=new JDKProxyFactory();
            PersonService service=(PersonService) factory.createProxyInstance(new PersonServiceBean("aaa"));
            service.save("bbb");
        }

    输出:

    begin invoking....
    save
    end invoking....

    如果目标对象没有实现任何接口

    使用cglib-nodep-2.1_3.jar

    public class CGlibProxyFactory implements MethodInterceptor{
        private Object targetObject;
        public Object createProxyInstance(Object targetObject){
            this.targetObject=targetObject;
            Enhancer enhancer=new Enhancer();
            enhancer.setSuperclass(this.targetObject.getClass());
            enhancer.setCallback(this);
            return enhancer.create();
        }
        @Override
        public Object intercept(Object proxy, Method method, Object[] args,
                MethodProxy methodProxy) throws Throwable {
            // TODO Auto-generated method stub
            PersonServiceBean bean=(PersonServiceBean) this.targetObject;
            Object result=null;
            if(bean.getUser()!=null){
                result=methodProxy.invoke(this.targetObject, args);
            }
            return null;
        }
    }
    有问题在公众号【清汤袭人】找我,时常冒出各种傻问题,然一通百通,其乐无穷,一起探讨


  • 相关阅读:
    python 递归一行实现字符串反转
    HABSE安装教程
    Target runtime Apache Tomcat v7.0 is not defined.
    论各种非人性化自动设置及关闭位置(持续更新中。。。)
    装饰者模式
    傻瓜式servlet监听器简单实例
    editplus代码格式化
    session,cookie机制
    servlet文件部署在tomcat上
    python学习笔记(一):作图
  • 原文地址:https://www.cnblogs.com/qingmaple/p/4052608.html
Copyright © 2020-2023  润新知