代理类和AOP

细节知多少 - spring boot transaction解析之阶段一 带有@Transactional方法的service类生成代理类的阶段 细节知多少 - spring boot transaction解析之阶段一 带有@Transactional方法的service类生成代理类的阶段 date: 2019-06-04 原文:spring boot transaction解析之阶段一 带有@Transactional方法的service类生成代理类的阶段 概述 spring boot transaction我们平时用着非常简单,只需要... 阅读详情

代理类和AOP

客户端不用调用目标对象了,直接调用代理类。最终目标方法还是去实行了。

  代理类的每个方法调用目标类的相同方法,并且在调用方法时候加上系统功能的代码

 

  代理和目标实现了相同的接口,有相同的方法。通过接口进行引用

  

  要为系统中的各种接口的类增加代理功能,那将需要太多的代理类,全部采用静态代理方法,非常麻烦。

  JVM可以在运行期间动态生成类的字节码,这样动态生成的类往往被用作代理类,即动态代理类。

  JVM生成的动态类必须实现一个或多个接口,所以,JVM生成的动态类只能用作具有相同接口的目标类的代理

  CGLIB库,可以动态生成一个类的子类(是一个个开源的库,不是sun公司的),一个类的子类也可以用作该类的代理,所以,如果要为一个没有实现接口的类生成动态代理类,那么可以使用CGLIB库

   代理类的各个方法通常除了要调用目标的响应方法和对外放回目标返回的结果外

  

通过Java 的API  

   getProxyClass 方法  返回字节码   需要告诉这个字节码实现了哪些接口  另外需要ClassLoader (每个Class都是由类加载器加载来的,就好像每个孩子都有妈妈一样) ,但是由内存出来的是没有经过类加载器哦!所以需要指定一个~!

   

  找个接口测试一下:

   

public class ProxyTest {
    public static void main(String[] args) {
     Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);  //找到Collection的接口(就是其字节码) 同时用这个接口相同的类加载器
        String name = clazzProxy.getName();//既然是个字节码就可以igetName()
        System.out.println(name);
    }
}

 

反正获取到了字节码,就玩字节码的那一套API就OK了,随便用

获取到构造方法:

  

public class ProxyTest {
    public static void main(String[] args) {
        Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);  //找到Collection的接口(就是其字节码) 同时用这个接口相同的类加载器
        String name = clazzProxy.getName();//既然是个字节码就可以igetName()
        System.out.println(name);

        System.out.println("开始打印构造函数相关");
        Constructor[] constructors = clazzProxy.getConstructors();
        for (Constructor c : constructors){
            String constructorName = c.getName();
            StringBuilder stringBuffer = new StringBuilder(name); //初始值
            stringBuffer.append('(');
            Class[] parameterTypes = c.getParameterTypes();
            for (Class clazzParam : parameterTypes){
                stringBuffer.append(clazzParam.getName()).append(',');
            }
            if (parameterTypes != null && parameterTypes.length == 0){
                stringBuffer.deleteCharAt(stringBuffer.length()-1); //删除掉最后那个字符
            }
            stringBuffer.append(')');
            System.out.println(stringBuffer);
        }

    }
}

打印结果: 

代理类:只有一构造方法 参数类型也一目了然,只有一个有参的构造方法。 参数是个新的类型哈,后面会说到他

 

 

代理类方法的获取:

public class ProxyTest {
    public static void main(String[] args) {
        Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);  //找到Collection的接口(就是其字节码) 同时用这个接口相同的类加载器
        System.out.println("打印所有方法:");;
        Method[] methods = clazzProxy.getMethods();
        for (Method m : methods){
            String methodName = m.getName();
            System.out.println("方法名字"+methodName);
            Class<?>[] parameterTypes = m.getParameterTypes();
            for (Class clazzParam : parameterTypes){
                System.out.println("方法类型"+clazzParam.getName());
            }
        }
    }
}

 

截了一部分图:

 

 

 

 下面我们创建动态代理类的实例对象,并且使用它的方法:

       

ublic interface InvocationHandler {

    /**
     * Processes a method invocation on a proxy instance and returns

是个接口,没法直接new对象,只能匿名对象。自己实现之

public class ProxyTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);  //找到Collection的接口(就是其字节码) 同时用这个接口相同的类加载器
        //clazzProxy.newInstance(); //搞到他的字节码了已经 但是没有不带参数的构造方法! 所以这么玩儿是不允许的!
        Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class); //做好有参的构造函数
        //内部类
        class MyInvocationHandler implements InvocationHandler{
            @Override    //实现它的方法  里面只有一个方法哦
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        }
        //实现的是Collection的接口哦 是Collection类的代理对象
        Collection proxy = (Collection)constructor.newInstance(new MyInvocationHandler());//此时传入真实的值  此时我们要看下InvocationHandler 到底是咋回事
        System.out.println(proxy);
        //proxy代理类是拥有Collection类中的所有方法哦

    }
}

创建了动态类,动态类去实例化对象,动态类的构造方法需要传入一个 InvocationHandler类的参数!

 

可以通过匿名内部类的方式:

public class ProxyTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);  //找到Collection的接口(就是其字节码) 同时用这个接口相同的类加载器
        //clazzProxy.newInstance(); //搞到他的字节码了已经 但是没有不带参数的构造方法! 所以这么玩儿是不允许的!
        Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class); //做好有参的构造函数

        //实现的是Collection的接口哦 是Collection类的代理对象
        Collection proxy = (Collection)constructor.newInstance(new InvocationHandler(){
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        });//此时传入真实的值  此时我们要看下InvocationHandler 到底是咋回事
        System.out.println(proxy);
        //proxy代理类是拥有Collection类中的所有方法哦

    }
}

 

 

总结:

  创建实现了Collection接口的动态类并查看其名称,分析Proxy.getProxyClass方法的各个参数

   编写列出动态类汇总的构所有构造方法和参数签名

   编写列出动态类中的所有方法和参数签名

 

  创建动态类的实例对象

     用反射获得构造方法

     编写一个最简单的InvocationHandler类

     调用构造方法创建动态类的实例对象,并将别写的InvocationHandler类的实例对象传进去

      答应创建的对象和调用对象的没有返回值的方法和getClass方法,演示调用其他有返回值的方法报告了异常

      将创建动态类的实例对象的代理改成匿名内部类的像是编写。

 

让jvm创建动态类及其实例对象,需要提供信息:

   三个方面:

    生成的类中有哪些方法,通过让其实现哪些接口的方式进行告知

     产生的类字节码必须有一个关联的类加载器对象

     生成的类中的方法的代码是怎样的,也得由我们提供。把我们的代码写在一个约定好了接口对象的方法中,把对象转给它,它调用我的方法。相当于插入了我的代码。提供执行代码的对象就是那个InvocationHandler对象,它是在创建动态类的实例对象的构造方法时候传递进去的。在上面的InvocationHandler对象的invke方法中加一点代码,又可以看到这些代码被调用执行了

 

可以把创建动态代理类和实例对象,一步到位: 用Proxy里面的一个方法就OK

 用Proxy.newInstance 方法直接一步就创建出代理对象  传入的参数:        类加载器, 接口数组 , handler

 

public class ProxyTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);  //找到Collection的接口(就是其字节码) 同时用这个接口相同的类加载器
        //clazzProxy.newInstance(); //搞到他的字节码了已经 但是没有不带参数的构造方法! 所以这么玩儿是不允许的!
        Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class); //做好有参的构造函数
      //Collection接口的类加载器
       Collection proxy = (Collection) Proxy.newProxyInstance(
               Collection.class.getClassLoader(), //这个接口的类加载器
               new Class[]{Collection.class},  //数组类型的字节码
               new InvocationHandler() {    //InvocationHandler 匿名内部类
                   @Override
                   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                       ArrayList target = new ArrayList();
                       System.out.println("返回之前加点代码");
                       Object returnValue  = method.invoke(target, args);
                       System.out.println("返回之后加点代码");
                       return returnValue;
                   }
               }
       );
       // 每次调用proxy 的方法, Handler的invoke方法就会被执行一次  都是处理全新的目标 target!
        proxy.add("toov5");
        proxy.add("代理类的方法");
        System.out.println(proxy.size());
    }
}

 

 将target挪出来!~

public class ProxyTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);  //找到Collection的接口(就是其字节码) 同时用这个接口相同的类加载器
        //clazzProxy.newInstance(); //搞到他的字节码了已经 但是没有不带参数的构造方法! 所以这么玩儿是不允许的!
        Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class); //做好有参的构造函数
      //Collection接口的类加载器
       Collection proxy = (Collection) Proxy.newProxyInstance(
               Collection.class.getClassLoader(), //这个接口的类加载器
               new Class[]{Collection.class},  //数组类型的字节码
               new InvocationHandler() {    //InvocationHandler 匿名内部类
                   ArrayList target = new ArrayList();
                   @Override
                   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                       System.out.println("返回之前加点代码");
                       Object returnValue  = method.invoke(target, args);
                       System.out.println("返回之后加点代码");
                       return returnValue;
                   }
               }
       );
       // 每次调用proxy 的方法, Handler的invoke方法就会被执行一次  都是处理全新的目标 target!
        proxy.add("toov5");
        proxy.add("代理类的方法");
        System.out.println(proxy.size());
    }
}

 

 

 

 

 分析:

  InvocationHandler对象的运行原理: 


 

 

  动态申城的类实现了Collection接口(可以实现若干接口),生成的类有Collection接口汇总的所有方法和一个如下接受InvocationHandler参数的构造方法

  构造方法接受一个Invocationhandler对象,接受对象了要干什么用呢? 该方法内部的代码会怎样呢?

 实现Collection接口中的各个方法的代码又是怎样的呢? InvocationHandler接口中定义的invoke方法接接受的三个参数又是什么意思? 

    

    Client程序嗲用objProxy.add("toov5") 方法时,涉及到三个要素: objProxy对象,add方法, “toov5”参数

      Class Proxy${

      add(Object objcet){

           return hanler.invoke(Object proxy, Method, Objcet[] args);

      }

 }

图示:

分析先打印动态代理的实例对象,结果为什么会是null呢? 调用有基本类型返回值的方法时为什么会空指针异常?

分析为什么动态代理的实例对象的getClass() 方法返回了正确的结果呢?   

 

 

分析动态代理的工作原理:

   怎样将目标类传进去?

       直接在InvocationHandler实现类中创建目标类的实例对象。可以看运行效果和加入实质代码,但是没有实际意义

       为InvocationHandler实现类注入目标类的实例对象,不能采用匿名内部类的形式了

      让匿名的InvocationHandler实现类访外面方法中的目标实现类实例对象final类型的引用变量

  

 

  

功能接口:

public interface Advice {
   void beforeMethod(Method method);
   void afterMethod(Method method);
}

功能接口实现类:

public class MyAdvice implements Advice{
    long beginTime = 0;
    @Override
    public void beforeMethod(Method method) {
        long beginTime = System.currentTimeMillis();
        System.out.println(method.getName()+"running start time"+beginTime);

    }

    @Override
    public void afterMethod(Method method) {
      long  endTime = System.currentTimeMillis();
        System.out.println(method.getName()+"running end time"+endTime);
     }

 

代理及其实现测试:

public class ProxyTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);  //找到Collection的接口(就是其字节码) 同时用这个接口相同的类加载器
        //clazzProxy.newInstance(); //搞到他的字节码了已经 但是没有不带参数的构造方法! 所以这么玩儿是不允许的!
        Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class); //做好有参的构造函数
      //Collection接口的类加载器

       final ArrayList target = new ArrayList();
        Collection proxy = (Collection)getProxy(target, new MyAdvice());
        // 每次调用proxy 的方法, Handler的invoke方法就会被执行一次  都是处理全新的目标 target!
        proxy.add("toov5"); //把代理穿进去 方法传进去 参数传递进去
    }

    private static Object getProxy( final Object target, final Advice advice){  //目标对象 功能对象
        Object proxy  =  Proxy.newProxyInstance(
                   target.getClass().getClassLoader(),
                    target.getClass().getInterfaces(),
                   new InvocationHandler() {    //InvocationHandler 匿名内部类
                       @Override
                       public Object invoke(Object proxy1, Method method, Object[] args) throws Throwable {
                          long beginTime = System.currentTimeMillis();
                           advice.beforeMethod(method);   //系统功能抽取成为了一个对象  通过接口形式
                           Object returnValue  = method.invoke(target, args);
                           advice.afterMethod(method);   //系统功能抽取成为了一个对象   通过接口形式
                           return returnValue;  //这个返回给代理
                       }
                   }
           );
        return proxy;
     }
}

 

posted @ 2019-05-19 22:25 toov5 阅读(...) 评论(...) 编辑 收藏

ComfyUI-controlnet控制出图 提供加载预处理器节点。 阅读详情

相关推荐

千兆以太网PHY设计:PCB原理图完整示例

深入解析千兆以太网PHY电路设计要点,提供完整的PCB原理图设计实例,帮助工程师掌握高速信号布局与电源去耦等关键技术,提升设计稳定性与信号完整性。

weixin_30633869的博客 631

设计模式【一】创建型模式(如何创建对象)

这是我第一次写博客,写的不好之处,请大家见谅(文章在不断的进行更新之中)

星空下的歌声 484

基于STM32的电子琴音乐播放器设计

​ 本设计以实际电路为最后的结果,实现了所有与其功能,具有重要的现实意义。件,在Proteus中进行原理图绘制,然后把 .hex文件下载到STM32F103RBT6中 进行仿真。由于网络上 下载的 Proteus中 没有 STM32F103RBT6这个芯片型号,我们又从网上 下载芯片 进行仿真。​ 本设计以实际电路为最后的结果,实现了所有与其功能,具有重要的现实意义。

TMMXA的博客 2万+

【设计模式】对象创建型模式

简单工厂模式

qq_43840665的博客 1035

通达信指标加密DLL加密解密三个公式源码准确率90%以上超级指标精准买卖绝世指标

通达信指标加密DLL加密解密三个公式源码准确率90%以上超级指标精准买卖绝世指标 1 超级指标 指标公式:买卖提示非常明显(适合通达信) 指标源码如下: M:3 100 60 N 3 100 30 散户线: 100*(HHV(HIGH,M)-CLOSE)/(HHV(HIGH,M)-LLV(LOW,M));RSV:=(CLOSE-LLV(LOW,N))/(HHV(HIGH,N)-LLV(LOW,N))*100; K:=SMA(RSV,5,1); D:=SMA(K,3,1); J:=3*K-2*D;主力

m0_60244077的博客 3万+

PID控制参数整定(调节方法)原理+图示+MATLAB调试

序 首先最重要的是了解每个参数调节了系统响应的那些属性,通过观察响应从而调节参数改变属性。 PID的作用概述: 1、P产生响应速度和力度,过小响应慢,过大会产生振荡,是I和D的基础。 2、I在有系统误差和外力作用时消除偏差、提高精度,同时也会增加响应速度,产生过冲,过大会产生振荡。 3、D抑制过冲和振荡,过小系统会过冲,过大会减慢响应速度。D的另外一个作用是抵抗外界的突发干扰,阻止系统的突变。 同时调节的顺序是:P>I>D 下面了解的一个很重要的就是调节的目标,也就是最好的响应曲线.

viafcccy的博客 16万+

设计模式(四):创建型之原型模式

用一个已经创建的实例作为原型,通过复制该原型对象来创建一个和原型对象相同的新对象。

从基础到源码解析的学习记录 1009

从零编写linux0.11 - 第二章 内核初始化

编程环境:Ubuntu Kylin 16.04 代码仓库:https://gitee.com/AprilSloan/linux0.11-project linux0.11源码下载(不能直接编译,需进行修改) 1.添加内核 进入内核后也不是马上进入main函数,上一章只是暂时设置gdt,此外还要设置idt和其他的一些初始化操作,这些内容也要使用汇编进行编写,此处采用AT&T格式的汇编。 以下为head.s的内容,为了简单起见,内容还是一个死循环。 .globl startup_32 startup_3

皓空Fly的博客 1265

设计模式:创建型模式-----单例模式

相关知识点: 1.概述 单例模式是java中最简单的设计模式之一,它提供了一种创建对象的最佳方式。 这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类。 2.使用单例模式的三个关键步骤 a.将构造方法私有化—防止外界创建对象 b.创建自己的对象 c.给外界访问方式 3.优缺点 优点: 提供了对唯一实例的受控访问。 由于在系统内存中只存在一个对象,因此可以节约系统资源。 允许可变数目的实例。 缺点: 单例类的扩

weixin_45873215的博客 155

保姆级教程:从OrthoFinder到CAFE5,手把手搞定基因家族收缩扩张分析(附完整代码与避坑指南)

本文提供从OrthoFinder到CAFE5的基因家族收缩扩张分析全流程教程,涵盖数据预处理、系统发育树准备、CAFE5运行与参数优化等关键步骤。通过详细代码示例和避坑指南,帮助研究者高效完成基因家族进化分析,特别适合生物信息学初学者。

dianshu1593的博客 391

AI智能体面试实战与真题解析: 312+道面试题完整答案 (下篇)

本文覆盖220道基础八股文+92道项目面试题,涵盖Agent架构、RAG、工具调用、记忆系统、多智能体、大模型基础、工程化实践、Prompt工程9大模块,含完整代码实现和模拟面试剧本。

program哲学 301

创建型模式的特点和分类——小马同学@Tian

创建型模式的特点和分类 创建型模式的主要关注点是“怎样创建对象?”,它的主要特点是“将对象的创建与使用分离”。这样可以降低系统的耦合度,使用者不需要关注对象的创建细节,对象的创建由相关的工厂来完成。就像我们去商场购买商品时,不需要知道商品是怎么生产出来一样,因为它们由专门的厂商生产。 创建型模式分为以下几种。 单例(Singleton)模式:某个类只能生成一个实例,该类提供了一个全局访问点供外部获取该实例,其拓展是有限多例模式。 原型(Prototype)模式:将一个对象作为原型,通过对其进行复制而克隆出

SigleDog的博客 308

【MTK平台】【wpa_supplicant】关于wpa_supplicant/p2p_supplicant.c文件的介绍

本文主要介绍external/wpa_supplicant_8/wpa_supplicant/p2p_supplicant.c 这个文件这个文件里面有个核心的方法就是。

专业开发者的博客,一个从事Android WiFi和蓝牙的工程师 725

Spring AOP之基于代理类的AOP实现和AspectJ开发

一,什么是AOP AOP全称是Aspect-Oriented Programming,即面向切面编程。AOP采用横向抽取的机制,将分散在各个方法中的重复代码提取出来,然后在程序编译或运行时,在将这些提取出来的代码应用到需要执行的地方。 二,AOP术语 Aspect(切面):通常指封装着用于横向插入系统功能的类 JointPoint(连接点):在程序执行过程中的某个阶段点。在Spring...

Isaac Lin 1398

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

spring AOP代理类分析(代理类和被代理类的关系)

使用 AopContext.currentProxy()获取代理类后调用私有方法,私有方法里面使用注入的对象方法,报空指针异常。

编程笔记 974

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

spring FrameWork 第六章:AOP代理和代理类的对比

先配置spring相关的jar包,需要额外添加aop的库: 定义一个持久层接口:userDao package com.aop; public interface UserDao { public void addUser(String id, String name); } 实现该接口的功能: package com.aop; public class UserDaoImpl implements UserDao { @Override public void a..

逼哥很疯狂的博客 169

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

spring aop实现类似代理类和类中的方法(注解实现)

1.可以指定aop的执行次序 2.@within,可以拦截类上有@DataSource注解的类中的所有方法 3.@annotation可以拦截有注解@DataSource的方法 4.两者结合可以实现类似Spring注解事务的效果,即可以在类上注解,让aop代理所有方法,也可以在方法上注解覆盖类的注解。

y_wave的专栏 2808

Spring AOP:被代理类的构造函数和调用自身类方法的注意点

Spring AOP是通过动态代理实现的:通过JDK的动态代理或者CGLIB动态生成子类. 如果被代理的bean是interface,会使用JDK的动态代理,这时候,bean的构造函数只会被调用一次,如果该bean没有实现任何interface,会使用cglib来动态生成子类,这时候构造函数会被调用两次,所以在bean的构造函数里尽量不要写业务相关的代码. 如果bean的某个方法被'AOP'了

交换一个思想,能得到俩思想 6491

AOP代理类(AOP Proxy) 分为jdk动态代理和cglib代理,两个代理方式的原理

分类 JDK代理类:        目标类 和 代理类实现相同的的接口 CGLIB代理类       代理类 是 目标类的子类,依赖CGLIB.JAR     JDK的动态代理主要涉及到java.lang.reflect包中的两个类:Proxy和InvocationHandler。其中InvocationHandler是一个接口,可以通过实现该接口定义横切逻辑,在并通过反射机制调用目标类...

nana_qq的专栏 248

Spring AOP、代理、基于代理类的AOP实现、AspectJ开发

文章目录1 AOP1.1 AOP简介1.2 AOP术语2 代理2.1 静态代理2.2 动态代理2.2.1 JDK动态代理2.2.2 基于CGLIB实现动态代理3 基于代理类的AOP实现3.1 Spring的通知类型3.2 ProxyFactoryBean4 AspectJ开发4.1 概述4.2 两种声明式AspectJ4.2.1 基于XML的声明式AspectJ4.2.2 基于注解的声明式AspectJ 1 AOP 1.1 AOP简介   AOP(Aspect-Oriented Programming),即

Haa__的博客 821

Spring | Srping AOP (AOP简介、动态代理、基于“代理类”的AOP实现)

Spring的AOP模块,是Spring框架体系结构中十分重要的内容,该模块中提供了面向切面编程实现。AOP的全称是,即面向切面编程( 也称面向方面编程 )它是面向对象编程(OOP)的一种补充,目前已成为一种比较成熟的编程方式。在传统的业务处理代码中,通常都会进行事务处理日志记录等操作。虽然使用OOP可以通过组合或者继承的方式来达到代码的重用,但如果要实现某个功能(如日志记录),同样的代码仍然会分散到各个方法中。这样,如果想要关闭某个功能,或者对其进行修改,就必须要修改所有的相关方法。 .....

m0_70720417的博客 1381

Spring中AOP的实现

1、概述 它最大的作用是什么? 在不更改源代码的情况下,对其原有功能进行增强。使得代码的重用率、开发效率、维护产生极大的方便。 运用场景 最常见的有:事务、日志、请求拦截等 2、使用 如何在Spring中使用AOP? 1、开启配置 @EnableAspectJAutoProxy 2、写代理类和被代理的类 @Component @Aspect public class AopConfig { @PostConstruct public void init(){ System.out.pri

苦行僧 848

获取泛型t的参数class_Spring AOP代理类获取泛型参数问题

环境描述:spring boot 2.x、jdk1.8问题描述:在使用AOP时,当获取到CGLIB代理对象类Class之后,在判断代理类Class是否包含泛型时与被代理类返回结果不一致,在项目中M990001_Service所实现接口包含泛型对于目标类的泛型操作具体代码如下当未使用AOP操作M990001_Service时,此时传入的是目标类对象,并且代码行判断是通过的if (type insta...

weixin_36372623的博客 1498

spring注解-AOP动态代理-@EnableAspectJAutoProxy注解如何工作

一.概述 AOP面向切面编程,生成目标方法所属类的代理类。代理类和目标类的关系:代理类继承目标类,并重载了目标类的方法。 代理类重载方法体里加入了切面业务逻辑和目标类方法的调用。 用户如何使用:从容器中获取目标类,实际上是获取代理类的实例, 代理类实例调用重载了父类的方法,就实现了AOP。 二.步骤 1.在配置类上添加@EnableAsp...

weixin_30466039的博客 2993

Spring AOP 源码探索 之深入解析实例化Bean过程创建代理类$Proxy

文章目录实例化切面通知AspectJAdviceAOP创建代理类的过程postProcessAfterInitializationwrapIfNecessary创建代理对象的调用链getAdvicesAndAdvisorsForBean方法的调用链 实例化切面通知AspectJAdvice 之前已经分析了实例化切面通知AspectJAdvice的过程。 那么接下来分析,根据切面通知(AspectJ...

weixin_42213903的博客 912
上一篇: Java8的时间日期API
下一篇: MySQL实战笔记:怎么给字符串字段加索引
Art&Code
博客等级 码龄7年 77粉丝 554原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值