Spring中的AOP

【Spring Boot】Spring AOP中的环绕通知 AspectOrientedProgramming(面向切面编程)AOP是Spring框架的第核(第核是IoC)AOP是一种思想,是对某一类事情的集中处理。其中在下面的学习中我们会学习到拦截器、统一异常处理,统一结果处理等,这些都是运用了AOP的统一思想来实现的。拦截器实现AOP思想作用的维度是前端对后端进行的一次请求和一次响应,主要是检索前端传来的URL,如果检索后返回True,则可以进入Controller开始执行代码,如果返回的为False,则表示失败,直接被拦截在外面,无法执行代码。 阅读详情
 
Spring 中的 AOP
创建时间: 2007年1月27日星期六
一、概述
(一)基本概念
1、什么是AOP?
    面向方面编程。所谓方面即是指日志、权限、异常处理、事务处理等。
2、AOP的3个关键概念
   (1 )切入点(Pointcut ):Pointcut是Join Point的集合,Join Point就是需要注入Adivce的位置,也就是需要插入日志输出代码、事务处理代码等“方面”(Aspect,也就是AOP中的A)代码的地方。
    比如我现在要写一个存钱的方法:saving()
    通常情况下我就得在这个saving()方法前后写些事务代码
    如:
 
          logger.log(Level.INFO,”start”);
Saving();
                         logger.log(Level.INFO,”end”);
      
         对于事务代码而言,saving()方法的前后就都是Join Point了。在Spring中它对应config.xml中设定的方法,这个方法就是类(class)中需要进行某方面处理的方法(method)。
         (2 )通知(Advice ):就是指Join Point对应的代码(方法)。比如日志输出这个方面,指的就是日志输出的代码或方法了。在Spring中,它对应类(class)。
        (3 )Advisor :是Poincut和Advice的配置器,它包括Pointcut和Advice,是将Advice注入程序中Pointcut位置的代码。在Sping中,它对应config.xml中的配置段 <bean id=logAdvisor class=”org.springframework.aop.support.RegexpMethodPointcutAdvisor”>。
  <bean id=”logAdvisor” class=”org.springframework.aop.support.RegexpMetho
dPointcutAdvisor”>
    //advice 属性对应的当然就是输出日志的类,也就是 ① 对应的那个bean
    <property name=”advice”>
         <ref bean=”log”/>
    </property>
   //patterns 属性指出指定要代理的方法,使用的是正则表达式
    <property name=”patterns”>
         <value>.*doAuditing.*</value>
    </property>
</bean>
 
(二)框架图

 

创建代理的两种方法
ProxyFactoryBean
动态代理
 
Spring4 种 Advice
Interception Around
Before
After Returning
Throw
 
两种代理方式
Java 动态代理
CGLIB 代理
 

(三)何时使用什么
 1、创建代理的两种方法中首选动态代理。
第1种:针对 某个类jakarta-oro-2.0.8.jar包。进行配置。可以指定某个类中所有方法都调用方面,也可以指定某个类中的某个方法,此时由于用到正则表达式,于是需要引入
第2种:针对 某个方法进行配置。
 2、Spring4种Advice:
      第1种:在需要调用方面的方法 前后都调用处理方面的代码
      第2种:在需要调用方面的方法 之前调用处理方面的代码
第3种:在需要调用方面的方法 之后都调用处理方面的代码
第4种:在需要调用方面的方法 发生异常时调用处理方面的代码
3、两种代理方式首选第1种。
          第1种:面向接口,必须先定义接口,这是好的习惯,应该提倡
          第2种:当没有接口的时候,可以使用这种方法。需引入cglib-nodep-2.1_3,jar包。
二、详细
(一)、创建AOP代理的两种方法:
1、用ProxyFactoryBean创建AOP代理
   (需要指明代理目标类)
(1)代理目标类的所有方法
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
 "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
// 下面 interceptorNames 属性(property)中的value值就是这个bean的id,其主要对应的是写入日志的那个类,也就是Spring AOP概念中的Advice(通知)。
①<bean id=" log" class="com.gc.action.LogAround"/>
// 要输出日志的那个类(因为这种方法必须要指明代理目标类)
②<bean id="timeBook" class="com.gc.action. timeBook "/>
// 下面开始定义代理类,也就是ProxyFactoryBean,这是Spring自带的类,这也是Spring AOP中的Advisor
<bean id=”logProxy” class=”org.springframework.aop.framework. ProxyFactor
yBean”>
 // 第一个属性,是指明要代理的类的接口,因为这个例子中使用的是Java动态代理机制来实现AOP的,因此必须指明接口
    <property name=”proxyInterfaces”>
        <value>com.gc.impl.TimeBookInterface</value>
    </property>
// 这个属性是指明代理目标(target)类,也就是 ② 定义的那个类
    <property name=”target”>
        <ref bean=”timeBook”/>
    </property>
[U1]  // 这个属性是用来指明插入哪个Advice,此处使用list,应该表示这个类不只是可以调用这一个log类
    <property name=”interceptorNames”>
         <list>
              <value>log</value> // 这个值(log)对应 ① 中定义的那个id为log的bean
         </list>
    </property>
[U2] </bean>
</beans>
(2)代理目标类的指定方法
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
 "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
①<bean id=" log" class="com.gc.action.LogAround"/>
<bean id="timeBook" class="com.gc.action. timeBook "/>
// 在上一段配置文件中添加了下面这个bean,用来指明要输出日志的指定方法(上一个例子是所有方法都输出日志)
<bean id=”logAdvisor” class=”org.springframework.aop.support.RegexpMetho
dPointcutAdvisor”>
    //advice 属性对应的当然就是输出日志的类,也就是 ① 对应的那个bean
    <property name=”advice”>
         <ref bean=”log”/>
    </property>
   //patterns 属性指出指定要代理的方法,使用的是正则表达式
    <property name=”patterns”>
         <value>.*doAuditing.*</value>
    </property>
</bean>
<bean id=”logProxy” class=”org.springframework.aop.framework. ProxyFactor
yBean”>
    <property name=”proxyInterfaces”>
        <value>com.gc.impl.TimeBookInterface</value>
    </property>
    <property name=”target”>
        <ref bean=”timeBook”/>
    </property>
    <property name=”interceptorNames”>
         <list>
              <value>log</value>
         </list>
    </property>
</bean>
</beans>
 
2、用DefaultAdvisorAutoProxyCreator创建自动代理
   (好处:不用指明代理目标类,如果一个大项目中有很多类也不必一个一个设置AOP代理)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
 "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id=" log" class="com.gc.action.LogAop"/>
<bean id="timeBook" class="com.gc.action. timeBook "/>
// 使用DefaultAdvisorAutoProxyCreator(红色代码)替代ProxyFactoryBean(绿色代码),因为绿色代码的作用是为具体的类(即所谓代理目标类)设置advice。
<bean id=”autoProxyCreator” class=”org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator”>
<bean id=” logAdvisor [U3] ” class=”org.springframework.aop.support.RegexpMetho
dPointcutAdvisor”>
     <property name=”advice”>
         <ref bean=”log”/>
    </property>
     <property name=”patterns”>
         <value>.*doAuditing.*</value> [U4] 
    </property>
</bean>
/*<bean id=”logProxy” class=”org.springframework.aop.framework.ProxyFactor
yBean”>
    <property name=”proxyInterfaces”>
        <value>com.gc.impl.TimeBookInterface</value>
    </property>
    <property name=”target”>
        <ref bean=”timeBook”/>
    </property>
    <property name=”interceptorNames”>
         <list>
              <value>log</value>
         </list>
    </property>
</bean>*/
</beans>
 
3、总结
实际上,DefaultAdvisorAutoProxyCreator和ProxyFactoryBean就是两种代理类,前者是自动的将Advisor和目标类联系起来,后者是通过指定的方式,将目标类和Advisor组合起来。
而advisor,对应的就是org.springframework.aop.support. RegexpMethodPointcutAdvisor,通过正则表达式来匹配类中的方法(设定Pointcut)。
(二)Spring四种通知(Advice)形式
1、Interception Around通知
       (1)负责输出日志的类
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
 
public class LogAround implements MethodInterceptor{
      private Logger logger = Logger.getLogger(this.getClass().getName());
   
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
           logger.log(Level.INFO, methodInvocation.getArguments()[0] + " 开始审核数据 ...."); 
        try {
          Object result = methodInvocation.proceed();
          return result;
        }
        finally {
                 logger.log(Level.INFO, methodInvocation.getArguments()[0] + " 审核数据结束 ....");
        }       
   }
}      
 (2)配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
 "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id=" log" class="com.gc.action.LogAop"/>
<bean id="timeBook" class="com.gc.action. timeBook "/>
<bean id=”logProxy” class=”org.springframework.aop.framework.ProxyFactor
yBean”>
    <property name=”proxyInterfaces”>
        <value>com.gc.impl.TimeBookInterface</value>
    </property>
    <property name=”target”>
        <ref bean=”timeBook”/>
    </property>
    <property name=”interceptorNames”>
         <list>
              <value>log</value>
         </list>
    </property>
</bean>
</beans>
 
 
2、Before通知
(1)负责输出日志的类
import java.lang.reflect.Method;
 
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;
 
public class LogBefore implements MethodBeforeAdvice {
       private Logger logger = Logger.getLogger(this.getClass().getName());
   
    public void before(Method method, Object[] args, Object target) throws Throwable {
              logger.log(Level.INFO, args[0] + " 开始审核数据....");
   }
}
(2)配置文件
     与第1 种方法相同。
3、After Returning通知
(1)负责输出日志的类
import java.lang.reflect.Method;
 
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;
 
public class LogAfterReturning implements AfterReturningAdvice {
       private Logger logger = Logger.getLogger(this.getClass().getName());
   
    public void afterReturning(Method method, Object[] args, Object target) throws Throwable {
              logger.log(Level.INFO, args[0] + " 开始审核数据....");
   }
}
(2)配置文件
     与第1 种方法相同。
4、Throw通知
(1)负责输出日志的类
import java.lang.reflect.Method;
 
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.aop.ThrowsAdvice;
 
public class LogThrow implements ThrowsAdvice {
       private Logger logger = Logger.getLogger(this.getClass().getName());
   
    public void afterThrowing(Method method, Object[] args, Object target,Throwable subclass) throws Throwable {
              logger.log(Level.INFO, args[0] + " 开始审核数据....");
   }
}
(2)配置文件
     与第1 种方法相同。
5、测试程序
   (1)使用自动代理
public class TestHelloWorld {
       public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
              ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml");
              TimeBookInterface timeBookProxy = (TimeBookInterface)actx.getBean("timeBook");
              timeBookProxy.doAuditing("张三");
   (2)不使用自动代理
public class TestHelloWorld {
       public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
              ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml");
              TimeBookInterface timeBookProxy = (TimeBookInterface)actx.getBean("logProxy");
              timeBookProxy.doAuditing("张三");
使用自动代理,则直接调用该类的名字(timeBook),否则调用相应的代理bean(logProxy)。因为第1种方法中根本就没有对应的代理bean,只有一个Spring的自动代理类
 
(三)Spring两种代理方式
1、Java动态代理
(1)配制文件(不使用自动代理)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
 "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id=" log" class="com.gc.action.LogAop"/>
<bean id="timeBook" class="com.gc.action. timeBook "/>
<bean id=”logProxy” class=”org.springframework.aop.framework.ProxyFactor
yBean”>
    <property name=”proxyInterfaces”>
        <value>com.gc.impl.TimeBookInterface</value>
    </property>
    <property name=”target”>
        <ref bean=”timeBook”/>
    </property>
    <property name=”interceptorNames”>
         <list>
              <value>log</value>
         </list>
    </property>
</bean>
</beans>
 
(2)测试程序
public class TestHelloWorld {
       public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
              ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml");
              TimeBookInterface timeBookProxy = (TimeBookInterface)actx.getBean("logProxy");
              timeBookProxy.doAuditing("张三");
 
2、CGLIB代理
(1)配制文件(不使用自动代理)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
 "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id=" log" class="com.gc.action.LogAop"/>
<bean id="timeBook" class="com.gc.action. timeBook "/>
<bean id=”logProxy” class=”org.springframework.aop.framework.ProxyFactor
yBean”>
// 增加如下属性,就表示使用的是CGLIB代理(对目标类直接代理)
    <property name=”proxyTargetClass”>
        <value>true</value>
    </property>
   /* 然后去掉下面的属性,也就是说此种方法不需要面向接口,或不需要指出接口
<property name=”proxyInterfaces”>
        <value>com.gc.impl.TimeBookInterface</value>
    </property>*/
    <property name=”target”>
        <ref bean=”timeBook”/>
    </property>
    <property name=”interceptorNames”>
         <list>
              <value>log</value>
         </list>
    </property>
</bean>
</beans>
 
(2)测试程序
public class TestHelloWorld {
       public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
              ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml");
              TimeBookInterface timeBookProxy = (TimeBookInterface)actx.getBean("logProxy");
              timeBookProxy.doAuditing("张三");
 
 

 [U1]Join Point
 [U2]Advice
 [U3]这个名字自己可以随便起
 [U4]如果想对类的所有方法都有效,就要写成.*.*
 
Spring AOP 面向切面 阅读详情

相关推荐

OpenClaw与Ollama本地AI部署指南

AI模型本地化部署是当前企业数字化转型的关键技术,通过开源框架Ollama可以在消费级硬件上运行大语言模型。本文以OpenClaw多智能体系统为例,详解从环境配置到模型优化的全流程实践,特别针对国内开发者遇到的网络问题提供了镜像加速等解决方案。这种私有化部署方案尤其适合金融数据分析、企业知识管理等对数据安全要求高的场景,通过模块化设计实现多智能体协作,同时保持对NVIDIA显卡和普通CPU的兼容性。

weixin_34302561的博客 408

详解Spring AOP

Aspect Oriented Programming(面向切面编程),OOP是面向对象编程(开发的时候把一个个都抽象成对象来开发),两者的维度不同,处理的事情不同切⾯就是指某⼀类特定问题, 所以AOP也可以理解为⾯向特定⽅法编程。面向切面编程就是针对某一类特定问题统一进行编程比如people类有自己的属性和行为,但是有小一部分人生病要去医院看病,看病这个业务逻辑就不属于哪一个类,因为people泛指所有人,所有人不会都看病。

N_0050的博客 2032

车辆动力学仿真模型的可信度评估方法

以转向工况测试为例,实车采集的方向盘转角作为车辆动力学模型的输入,记录车辆动力学模型的横摆角速度的输出结果,计算横摆角速度的幅频特性,根据《GB/T 6323-2014 转向盘角脉冲试验》的方法,获取横摆角速度峰值、横摆角速度谐振峰频率、横摆角速度谐振峰水平,与采集的实车结果对比,并计算车辆动力学模型和实车对于关键对比参数的相对误差。由公式(2)计算可得,在制动工况和转向工况测试下,车辆动力学模型和实车的纵向车速、制动减速度、制动距离、横摆角速度基本一致,精度> 85%,具有较好的精度。

wangchen900705的博客 1967

Spring AOP详细介绍

什么是AOP AOP(Aspect-OrientedProgramming,面向切面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善。OOP引入封装、继承和多态性等概念来建立一种对象层次结构,用以模拟公共行为的一个集合。当我们需要为分散的对象引入公共行为的时候,OOP则显得无能为力。也就是说,OOP允许你定义从上到下的关系,...

JinXYan的博客 7万+

从C到汇编:单片机汇编语言核心概念迁移指南

本文详细介绍了从C语言迁移到单片机汇编语言的核心概念与实践指南,特别适合嵌入式开发者。文章深入探讨了汇编语言在性能优化、时序控制等方面的独特优势,并提供了变量存储、函数实现、流程控制等关键概念的对应关系,帮助开发者高效掌握汇编编程技巧。

weixin_31887307的博客 349

Apollo学习笔记(4)坐标系

百度Apollo项目用到了多种坐标系,其中帮助文档提及的坐标系包括: 全球地理坐标系(The Global Geographic coordinate system ) 局部坐标系—东-北-天坐标(The Local Frame – East-North-Up,ENU) 车身坐标系—右-前-天坐标(The Vehicle Frame —Right-Forward-Up,RFU) 车身坐标系—前-左-天坐标(The Vehicle Frame —Front-Left-Up,FLU) 还有一种Frenet坐标

qq_24649627的博客 5805

【Spring】AOP

AOP(Aspect Oriented Programming) 是一种编程范型,即面向切面编程。什么是面向切面编程?切面就是指某一类特定问题,所以AOP也可以理解为面向特定方法编程。面向编程旨在通过分离横切关注点来提高代码的模块化和可维护性,允许开发者将那些与业务逻辑无关,但又需要在多个地方使用的功能(如日志记录、事务管理、安全性等)从业务逻辑中分离出来。在前面我们的登录校验,用了拦截器,其实也是对AOP思想的一种实现。统一数据返回格式和统一异常处理也是AOP的一种实现。

zhyhgx的博客 1931

Altium Designer操作技巧(4)——如何利用嘉立创EDA来输出3D封装到AD封装库?

本文介绍了利用嘉立创EDA和FreeCAD软件为PCB元件添加3D模型的方法。首先在嘉立创EDA中搜索元件编号并导出3D模型,然后使用FreeCAD删除3D模型中的PCB基板部分,最后将处理后的3D模型导入PCB封装库并更新到PCB设计中。文章详细讲解了每个步骤的操作流程,包括模型导出、基板删除、位置调整等关键环节,并提供了解决常见问题的方法。通过这种方法,电子工程师可以快速获得元器件的3D模型,提高PCB设计的准确性。

u012526819的博客 2634

【Spring】Spring AOP

SpringAOP 认识和实现原理

bit me的博客 1951

UFS软件分区介绍

本文主要介绍了ufs软件分区管理的概况,能够使大家对软件分区有个大体的认识

肥匪斐's blogs 1万+

以 Joule 驱动的生成式开发:把需求文档直接变成可运行的 SAP 应用

摘要:SAP BTP的AI助手Joule正在改变开发方式,支持从自然语言描述自动生成数据模型、服务、UI及测试代码。在SAP Business Application Studio中,Joule能根据业务需求生成结构化代码,并提供代码补全、重构、解释等功能。开发者需注意避免上传敏感数据,并对AI生成的代码进行人工审核。Joule特别针对ABAP开发进行了优化,提供符合SAP规范的代码建议,帮助迁移遗留系统。此外,它还能快速生成CAP项目原型,但所有AI生成内容都需经过严格测试验证。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 357

Spring AOP—2、Spring中的AOP能为我们做些什么

在介绍Spring的AOP功能前,先总结下几个AOP的概念,下面的几个AOP概念不是Spring指定的,而是AOP本身就有的。看看这些专业术语: Aspect:将对多个类的关注进行统一的模块。在Spring里面是一个普通的类,这个类相当于一个模块,里面包含了对各种类的所有关注,使用@Aspect来表示这个类是一个表明关注方面的类。 Join point:连接点,一个程序执行中的某个点,例如一个

rdarda的专栏 2512

基于Simulink的电力电子系统电磁兼容性(EMC)仿真

在电力电子系统中,由于高频开关器件的存在,会产生大量的电磁干扰(EMI),这对系统的稳定性和可靠性提出了挑战。Simulink 提供了一个强大的仿真环境,可以用来设计、分析和验证电力电子系统的电磁兼容性。本教程将详细介绍如何使用 Simulink 进行电力电子系统的电磁兼容性仿真。通过本教程,我们详细介绍了如何使用 Simulink 进行电力电子系统的电磁兼容性仿真。为了模拟电力电子系统中的电磁干扰(EMI),我们需要添加噪声源模块。为了更好地分析系统的电磁兼容性特性,可以在模型中添加频谱分析工具。

amy_mhd的博客 1135

Spring中的AOP(一)——AOP基本概念和Spring对AOP的支持

AOP的基本概念     AOP从运行的角度考虑程序的流程,提取业务处理过程的切面。AOP面向的是程序运行中的各个步骤,希望以更好的方式来组合业务逻辑的各个步骤。AOP框架并不与特定的代码耦合,AOP框架能处理程序执行中特定切入点,而不与具体某个类耦合(即在不污染某个类的情况下,处理这个类相关的切点)。下面是一些AOP的一些术语:     切面(Aspect):业务流程运行的某个特定步

caomiao2006的专栏 2068

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

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

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Spring Boot中的Spring AOP全面解析

AOP本质:集中处理横切关注点(日志、事务、权限等)核心四要素:切点、连接点、通知、切面通知选择:简单逻辑 → 特定通知(Before/After)复杂控制 → 环绕通知切点表达式:规则匹配 → execution灵活匹配 → @annotation底层原理:接口实现 → JDK动态代理类继承 → CGLIB动态代理最佳实践口诀注解切面解耦强,环绕通知功能广表达式里慎用*,精准匹配性能涨多切面时定顺序,@Order来帮大忙循环依赖需警惕,三级缓存解彷徨。

2401_82686243的博客 1280

深度学习工具包 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】spring AOP的总结

目录 一、AOP的概念 1.1 术语 1.2 AspectJ 1.3 AOP和spring AOP有什么关系 二、spring AOP的使用 0、首先要引用AspectJ语法依赖 1、spring AOP开启AspectJ语法支持 2、声明一个切面(Aspect) 2.1、声明一个Pointcut切点 2.2 声明一个advice通知 四、advice通知的位置 一、A...

小七的博客 617

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Spring中的AOP的使用

Spring中的AOP的使用 1.1 什么是AOP AOP:全称是Aspect Oriented Programming即:面向切面编程。 简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。 1.2 AOP的作用及优势 作用: 在程序运行期间,不修改源码对已有方法进行增强。 优势: 减少重复代码 提高开发效率 维护方便。 1.3 AOP相关术语 Joinpoint(连接点): 所谓连接点是指那些被拦截到的点。在spring中,这

weixin_40055163的博客 1255

Spring 配置AOP Spring注解配置AOP Spring XML 配置AOP Spring Aspect AOP

Spring 配置AOP Spring注解配置AOP Spring XML 配置AOP Spring Aspect AOP

HaHa_Sir的博客 1139
上一篇: 为Delphi正名
下一篇: Delphi面向对象编程的20条规则(零雨其蒙评述版)
sslaowan
博客等级 码龄21年 3粉丝 31原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值