Spring AOP 详解

Spring AOP详解 一、AOP 1.1、AOP介绍 1.1.1、什么是AOP? 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从... 阅读详情

      此前对于AOP的使用仅限于声明式事务,除此之外在实际开发中也没有遇到过与之相关的问题。最近项目中遇到了以下几点需求,仔细思考之后,觉得采用AOP来解决。一方面是为了以更加灵活的方式来解决问题,另一方面是借此机会深入学习Spring AOP相关的内容。本文是权当本人的自己AOP学习笔记,以下需求不用AOP肯定也能解决,至于是否牵强附会,仁者见仁智者见智。

  1.     对部分函数的调用进行日志记录,用于观察特定问题在运行过程中的函数调用情况
  2. 监控部分重要函数,若抛出指定的异常,需要以短信或邮件方式通知相关人员
  3. 金控部分重要函数的执行时间

    事实上,以上需求没有AOP也能搞定,只是在实现过程中比较郁闷摆了。

  1. 需要打印日志的函数分散在各个包中,只能找到所有的函数体,手动添加日志。然而这些日志都是临时的,待问题解决之后应该需要清除打印日志的代码,只能再次手动清除^_^!
  2. 类 似1的情况,需要捕获异常的地方太多,如果手动添加时想到很可能明天又要手动清除,只能再汗。OK,该需求相对比较固定,属于长期监控的范畴,并不需求临 时添加后再清除。然而,客户某天要求,把其中20%的异常改为短信提醒,剩下的80%改用邮件提醒。改之,两天后,客户抱怨短信太多,全部改成邮件提 醒...
  3. 该需求通常用于监控某些函数的执行时间,用以判断系统执行慢的瓶颈所在。瓶颈被解决之后,烦恼同情况1


    终于下定决心,采用AOP来解决!代码如下:

    切面类TestAspect

Java代码 复制代码 收藏代码
  1. package com.spring.aop; 
  2. /**
  3. * 切面
  4. *
  5. */ 
  6. public class TestAspect { 
  7.  
  8.     public void doAfter(JoinPoint jp) { 
  9.         System.out.println("log Ending method: " 
  10.                 + jp.getTarget().getClass().getName() + "." 
  11.                 + jp.getSignature().getName()); 
  12.     } 
  13.  
  14.     public Object doAround(ProceedingJoinPoint pjp) throws Throwable { 
  15.         long time = System.currentTimeMillis(); 
  16.         Object retVal = pjp.proceed(); 
  17.         time = System.currentTimeMillis() - time; 
  18.         System.out.println("process time: " + time + " ms"); 
  19.         return retVal; 
  20.     } 
  21.  
  22.     public void doBefore(JoinPoint jp) { 
  23.         System.out.println("log Begining method: " 
  24.                 + jp.getTarget().getClass().getName() + "." 
  25.                 + jp.getSignature().getName()); 
  26.     } 
  27.  
  28.     public void doThrowing(JoinPoint jp, Throwable ex) { 
  29.         System.out.println("method " + jp.getTarget().getClass().getName() 
  30.                 + "." + jp.getSignature().getName() + " throw exception"); 
  31.         System.out.println(ex.getMessage()); 
  32.     } 
  33.  
  34.     private void sendEx(String ex) { 
  35.         //TODO 发送短信或邮件提醒 
  36.     } 
  37. }  
package com.spring.aop;
/**
 * 切面
 *
 */
public class TestAspect {

    public void doAfter(JoinPoint jp) {
        System.out.println("log Ending method: "
                + jp.getTarget().getClass().getName() + "."
                + jp.getSignature().getName());
    }

    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long time = System.currentTimeMillis();
        Object retVal = pjp.proceed();
        time = System.currentTimeMillis() - time;
        System.out.println("process time: " + time + " ms");
        return retVal;
    }

    public void doBefore(JoinPoint jp) {
        System.out.println("log Begining method: "
                + jp.getTarget().getClass().getName() + "."
                + jp.getSignature().getName());
    }

    public void doThrowing(JoinPoint jp, Throwable ex) {
        System.out.println("method " + jp.getTarget().getClass().getName()
                + "." + jp.getSignature().getName() + " throw exception");
        System.out.println(ex.getMessage());
    }

    private void sendEx(String ex) {
        //TODO 发送短信或邮件提醒
    }
} 

Java代码 复制代码 收藏代码
  1. package com.spring.service; 
  2. /**
  3. * 接口A
  4. */ 
  5. public interface AService { 
  6.      
  7.     public void fooA(String _msg); 
  8.  
  9.     public void barA(); 
  10. } 
package com.spring.service;
/**
 * 接口A
 */
public interface AService {
    
    public void fooA(String _msg);

    public void barA();
}
Java代码 复制代码 收藏代码
  1. package com.spring.service; 
  2. /**
  3. *接口A的实现类
  4. */ 
  5. public class AServiceImpl implements AService { 
  6.  
  7.     public void barA() { 
  8.         System.out.println("AServiceImpl.barA()"); 
  9.     } 
  10.  
  11.     public void fooA(String _msg) { 
  12.         System.out.println("AServiceImpl.fooA(msg:"+_msg+")"); 
  13.     } 
  14. } 
package com.spring.service;
/**
 *接口A的实现类
 */
public class AServiceImpl implements AService {

    public void barA() {
        System.out.println("AServiceImpl.barA()");
    }

    public void fooA(String _msg) {
        System.out.println("AServiceImpl.fooA(msg:"+_msg+")");
    }
}

Java代码 复制代码 收藏代码
  1. package com.spring.service; 
  2.  
  3. /**
  4. *   Service类B
  5. */ 
  6. public class BServiceImpl { 
  7.  
  8.     public void barB(String _msg, int _type) { 
  9.         System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")"); 
  10.         if(_type == 1) 
  11.             throw new IllegalArgumentException("测试异常"); 
  12.     } 
  13.  
  14.     public void fooB() { 
  15.         System.out.println("BServiceImpl.fooB()"); 
  16.     } 
  17.  
  18. } 
package com.spring.service;

/**
 *   Service类B
 */
public class BServiceImpl {

    public void barB(String _msg, int _type) {
        System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")");
        if(_type == 1)
            throw new IllegalArgumentException("测试异常");
    }

    public void fooB() {
        System.out.println("BServiceImpl.fooB()");
    }

}

    ApplicationContext

Java代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  4.     xmlns:aop="http://www.springframework.org/schema/aop" 
  5.     xsi:schemaLocation=" 
  6.             http://www.springframework.org/schema/beans 
  7.             http://www.springframework.org/schema/beans/spring-beans-2.0.xsd 
  8.             http://www.springframework.org/schema/aop 
  9.             http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" 
  10.     default-autowire="autodetect"> 
  11.     <aop:config> 
  12.         <aop:aspect id="TestAspect" ref="aspectBean"> 
  13.             <!--配置com.spring.service包下所有类或接口的所有方法--> 
  14.             <aop:pointcut id="businessService" 
  15.                 expression="execution(* com.spring.service.*.*(..))" /> 
  16.             <aop:before pointcut-ref="businessService" method="doBefore"/> 
  17.             <aop:after pointcut-ref="businessService" method="doAfter"/> 
  18.             <aop:around pointcut-ref="businessService" method="doAround"/> 
  19.             <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/> 
  20.         </aop:aspect> 
  21.     </aop:config> 
  22.      
  23.     <bean id="aspectBean" class="com.spring.aop.TestAspect" /> 
  24.     <bean id="aService" class="com.spring.service.AServiceImpl"></bean> 
  25.     <bean id="bService" class="com.spring.service.BServiceImpl"></bean> 
  26.  
  27. </beans> 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
    default-autowire="autodetect">
    <aop:config>
        <aop:aspect id="TestAspect" ref="aspectBean">
            <!--配置com.spring.service包下所有类或接口的所有方法-->
            <aop:pointcut id="businessService"
                expression="execution(* com.spring.service.*.*(..))" />
            <aop:before pointcut-ref="businessService" method="doBefore"/>
            <aop:after pointcut-ref="businessService" method="doAfter"/>
            <aop:around pointcut-ref="businessService" method="doAround"/>
            <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/>
        </aop:aspect>
    </aop:config>
    
    <bean id="aspectBean" class="com.spring.aop.TestAspect" />
    <bean id="aService" class="com.spring.service.AServiceImpl"></bean>
    <bean id="bService" class="com.spring.service.BServiceImpl"></bean>

</beans>

    测试类AOPTest

Java代码 复制代码 收藏代码
  1. public class AOPTest extends AbstractDependencyInjectionSpringContextTests { 
  2.      
  3.     private AService aService; 
  4.      
  5.     private BServiceImpl bService; 
  6.      
  7.     protected String[] getConfigLocations() { 
  8.         String[] configs = new String[] { "/applicationContext.xml"}; 
  9.         return configs; 
  10.     } 
  11.      
  12.      
  13.     /**
  14.      * 测试正常调用
  15.      */ 
  16.     public void testCall() 
  17.     { 
  18.         System.out.println("SpringTest JUnit test"); 
  19.         aService.fooA("JUnit test fooA"); 
  20.         aService.barA(); 
  21.         bService.fooB(); 
  22.         bService.barB("JUnit test barB",0); 
  23.     } 
  24.      
  25.     /**
  26.      * 测试After-Throwing
  27.      */ 
  28.     public void testThrow() 
  29.     { 
  30.         try { 
  31.             bService.barB("JUnit call barB",1); 
  32.         } catch (IllegalArgumentException e) { 
  33.              
  34.         } 
  35.     } 
  36.      
  37.     public void setAService(AService service) { 
  38.         aService = service; 
  39.     } 
  40.      
  41.     public void setBService(BServiceImpl service) { 
  42.         bService = service; 
  43.     } 
  44. } 
public class AOPTest extends AbstractDependencyInjectionSpringContextTests {
	
	private AService aService;
	
	private BServiceImpl bService;
	
	protected String[] getConfigLocations() {
		String[] configs = new String[] { "/applicationContext.xml"};
		return configs;
	}
	
	
	/**
	 * 测试正常调用
	 */
	public void testCall()
	{
		System.out.println("SpringTest JUnit test");
		aService.fooA("JUnit test fooA");
		aService.barA();
		bService.fooB();
		bService.barB("JUnit test barB",0);
	}
	
	/**
	 * 测试After-Throwing
	 */
	public void testThrow()
	{
		try {
			bService.barB("JUnit call barB",1);
		} catch (IllegalArgumentException e) {
			
		}
	}
	
	public void setAService(AService service) {
		aService = service;
	}
	
	public void setBService(BServiceImpl service) {
		bService = service;
	}
}

    运行结果如下:

Java代码 复制代码 收藏代码
  1. log Begining method: com.spring.service.AServiceImpl.fooA 
  2. AServiceImpl.fooA(msg:JUnit test fooA) 
  3. log Ending method: com.spring.service.AServiceImpl.fooA 
  4. process time: 0 ms 
  5. log Begining method: com.spring.service.AServiceImpl.barA 
  6. AServiceImpl.barA() 
  7. log Ending method: com.spring.service.AServiceImpl.barA 
  8. process time: 0 ms 
  9. log Begining method: com.spring.service.BServiceImpl.fooB 
  10. BServiceImpl.fooB() 
  11. log Ending method: com.spring.service.BServiceImpl.fooB 
  12. process time: 0 ms 
  13. log Begining method: com.spring.service.BServiceImpl.barB 
  14. BServiceImpl.barB(msg:JUnit test barB type:0) 
  15. log Ending method: com.spring.service.BServiceImpl.barB 
  16. process time: 0 ms 
  17.  
  18. log Begining method: com.spring.service.BServiceImpl.barB 
  19. BServiceImpl.barB(msg:JUnit call barB type:1) 
  20. log Ending method: com.spring.service.BServiceImpl.barB 
  21. method com.spring.service.BServiceImpl.barB throw exception 
  22. 测试异常 
log Begining method: com.spring.service.AServiceImpl.fooA
AServiceImpl.fooA(msg:JUnit test fooA)
log Ending method: com.spring.service.AServiceImpl.fooA
process time: 0 ms
log Begining method: com.spring.service.AServiceImpl.barA
AServiceImpl.barA()
log Ending method: com.spring.service.AServiceImpl.barA
process time: 0 ms
log Begining method: com.spring.service.BServiceImpl.fooB
BServiceImpl.fooB()
log Ending method: com.spring.service.BServiceImpl.fooB
process time: 0 ms
log Begining method: com.spring.service.BServiceImpl.barB
BServiceImpl.barB(msg:JUnit test barB type:0)
log Ending method: com.spring.service.BServiceImpl.barB
process time: 0 ms

log Begining method: com.spring.service.BServiceImpl.barB
BServiceImpl.barB(msg:JUnit call barB type:1)
log Ending method: com.spring.service.BServiceImpl.barB
method com.spring.service.BServiceImpl.barB throw exception
测试异常

    《Spring参考手册》中定义了以下几个AOP的重要概念,结合以上代码分析如下:

  • 切面(Aspect):官方的抽象定义为“一个关注点的模块化,这个关注点可能会横切多个对象”,在本例中,“切面”就是类TestAspect所关注的具体行为,例如,AServiceImpl.barA()的调用就是切面TestAspect所关注的行为之一。“切面”在ApplicationContext中<aop:aspect>来配置。
  • 连接点(Joinpoint):程序执行过程中的某一行为,例如,AServiceImpl.barA()的调用或者BServiceImpl.barB(String _msg, int _type)抛出异常等行为。
  • 通知(Advice):“切面”对于某个“连接点”所产生的动作,例如,TestAspect中对com.spring.service包下所有类的方法进行日志记录的动作就是一个Advice。其中,一个“切面”可以包含多个“Advice”,例如TestAspect
  • 切入点(Pointcut):匹配连接点的断言,在AOP中通知和一个切入点表达式关联。例如,TestAspect中的所有通知所关注的连接点,都由切入点表达式execution(* com.spring.service.*.*(..))来决定
  • 目标对象(Target Object):被一个或者多个切面所通知的对象。例如,AServcieImpl和BServiceImpl,当然在实际运行时,Spring AOP采用代理实现,实际AOP操作的是TargetObject的代理对象。
  • AOP代理(AOP Proxy)在Spring AOP中有两种代理方式,JDK动态代理和CGLIB代理。默认情况下,TargetObject实现了接口时,则采用JDK动态代理,例如,AServiceImpl;反之,采用CGLIB代理,例如,BServiceImpl。强制使用CGLIB代理需要将 <aop:config>的 proxy-target-class属性设为true

       通知(Advice)类型

  • 前置通知(Before advice):在某连接点(JoinPoint)之前执行的通知,但这个通知不能阻止连接点前的执行。ApplicationContext中在<aop:aspect>里面使用<aop:before>元素进行声明。例如,TestAspect中的doBefore方法
  • 后通知(After advice):当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。ApplicationContext中在<aop:aspect>里面使用<aop:after>元素进行声明。例如,TestAspect中的doAfter方法,所以AOPTest中调用BServiceImpl.barB抛出异常时,doAfter方法仍然执行
  • 返回后通知(After return advice):在某连接点正常完成后执行的通知,不包括抛出异常的情况。ApplicationContext中在<aop:aspect>里面使用<after-returning>元素进行声明。
  • 环绕通知(Around advice):包围一个连接点的通知,类似Web中Servlet规范中的Filter的doFilter方法。可以在方法的调用前后完成自定义的行为,也可以选择不执行。ApplicationContext中在<aop:aspect>里面使用<aop:around>元素进行声明。例如,TestAspect中的doAround方法。
  • 抛出异常后通知(After throwing advice):  在方法抛出异常退出时执行的通知。 ApplicationContext中在<aop:aspect>里面使用<aop:after-throwing>元素进行声明。例如,TestAspect中的doThrowing方法。

       切入点表达式

  • 通常情况下,表达式中使用”execution“就可以满足大部分的要求。表达式格式如下:
Java代码 复制代码 收藏代码
  1. execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?) 
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)

modifiers-pattern:方法的操作权限

ret-type-pattern:返回值

declaring-type-pattern:方法所在的包

name-pattern:方法名

parm-pattern:参数名

throws-pattern:异常

其中,除ret-type-pattern和name-pattern之外,其他都是可选的。上例中,execution(* com.spring.service.*.*(..))表示com.spring.service包下,返回值为任意类型;方法名任意;参数不作限制的所有方法。

  • 通知参数

可以通过args来绑定参数,这样就可以在通知(Advice)中访问具体参数了。例如,<aop:aspect>配置如下

Java代码 复制代码 收藏代码
  1. <aop:config> 
  2.     <aop:aspect id="TestAspect" ref="aspectBean"> 
  3.         <aop:pointcut id="businessService" 
  4.             expression="execution(* com.spring.service.*.*(String,..)) and args(msg,..)" /> 
  5.             <aop:after pointcut-ref="businessService" method="doAfter"/> 
  6.     </aop:aspect> 
  7. </aop:config> 
	<aop:config>
		<aop:aspect id="TestAspect" ref="aspectBean">
			<aop:pointcut id="businessService"
				expression="execution(* com.spring.service.*.*(String,..)) and args(msg,..)" />
				<aop:after pointcut-ref="businessService" method="doAfter"/>
		</aop:aspect>
	</aop:config>

TestAspect的doAfter方法中就可以访问msg参数,但这样以来AService中的barA()和BServiceImpl中的barB()就不再是连接点,因为execution(* com.spring.service.*.*(String,..))只配置第一个参数为String类型的方法。其中,doAfter方法定义如下:

Java代码 复制代码 收藏代码
  1. public void doAfter(JoinPoint jp,String msg) 
public void doAfter(JoinPoint jp,String msg)
  •   访问当前的连接点

任何通知(Advice)方法可以将第一个参数定义为 org.aspectj.lang.JoinPoint类型。JoinPoint接口提供了一系列有用的方法, 比如 getArgs()(返回方法参数)、getThis()(返回代理对象)、getTarget()(返回目标)、getSignature()(返回正在被通知的方法相关信息)和 toString()(打印出正在被通知的方法的有用信息。

Spring AOP 详解:从入门到实战 本文详细介绍了Spring AOP的核心概念与实际应用。Spring AOP通过面向切面编程解决了企业应用中的横切关注点问题,与传统OOP形成互补。文章阐述了AOP的基本术语(切面、连接点、切点等)和五种通知类型,对比了注解和XML两种配置方式。重点分析了execution切点表达式语法,并通过代码示例展示了如何实现日志、事务和安全等常见切面功能。Spring AOP基于代理实现运行时织入,相比AspectJ更轻量但功能稍有限制。 阅读详情

相关推荐

Spring Aop详解

什么是AOP?AOP英文全称:Aspect Oriented Programming(面向切面编程、面向方面编程),其实说白了,面向切面编程就是面向特定方法编程。那什么又是面向方法编程呢,为什么又需要面向方法编程呢?来我们举个例子做一个说明:比如,我们这里有一个项目,项目中开发了很多的业务功能。然而有一些业务功能执行效率比较低,执行耗时较长,我们需要针对于这些业务方法进行优化。那首先第一步就需要定位出执行耗时比较长的业务方法,再针对于业务方法再来进行优化。

Delu3376451753的博客 1404

Spring AOP使用

目录Spring AOP 实现原理Spring AOP 使用方式Spring AOP通知顺序多个切面的执行顺序配置多个切面的执行顺序的方式@Pointcut注解@DeclareParents注解参考 AOP(Aspect-Oriented Programming,面向方面编程),可以看成OOP(Object-Oriented Programing,面向对象编程)的补充和完善。面向对象编程时,建立了一种对象层次结构,可以定义从上到下的关系,但不适合定义从左到右的关系。如日志功能。日志代码水平地散布在所有的对象

云原生Java Web领域技术博客 1153

11-4 AEB 算法原理及系统组成

本专题旨在探讨如何利用仿真软件开发自动紧急制动系统AEB,主要通过整理开发流程,实现从需求到验证的全流程掌握,为后续开发提供支持;同时,研究了如何在汽车自动驾驶仿真工具中开发自己的算法,并解决了从ISO、E-CNAP、GB/T以及交通法规等提炼出功能需求的问题,以快速实现原型模型的开发。本专题重点讲解了AEB的工作原理、系统/软件架构和需求、算法模型及实现、CCRs/CCRb/CCRm建模与仿真、VRU-AEB-B/P/M建模与仿真,同时还提供了测试用例,期待将AEB算法成功地产品化。

AIgraphX 8581

Spring AOP-@doAround学习

@Around("controllerAspect()") public Object doAround(ProceedingJoinPoint joinPoint) { Object result = null; try { result = joinPoint.proceed(); } catch (Throwable e) { e.printStackTr

做最好的自己 8247

Win10管理员权限的‘暗门’:从mmc.exe被阻止,聊聊UAC与自动提权那些事儿

本文深入解析Windows 10中UAC(用户账户控制)与自动提权机制,探讨mmc.exe被阻止的深层原因及解决方案。从UAC工作原理到自动提权机制,再到具体诊断与修复步骤,帮助用户理解并解决权限管理问题,同时平衡安全性与便利性。

weixin_30521161的博客 426

【论文笔记】LIME: low-light image enhancement via illumination map estimation

【论文笔记】LIME: low-light image enhancement via illumination map estimation 一篇低光图像增强,引用超1000次的经典论文

weixin_45565519的博客 1799

Spring笔记(三):Aop详解

1、需要的包:spring的包,还需要 aspectjweaver.jar,aopalliance.jar ,asm.jar 和cglib.jar 。 2、Aop的实现方式:Spring 接口方式,schema配置方式和注解的三种方式 3、概念 1)切面(aspect):用来切插业务方法的类。 2)连接点(joinpoint):是切面类和业务类的连接点,其实就是封装了业务方法的一些基本属性,作为通知的参数来解析。 3)通知(advice):在切面类中,声明对业务方法做额外处理的方法。 4)切入点(po

Sam Blog 3511

服务器安全配置:二、本地安全策略设置

密码最长使⽤期限”设置为“90天”;“⽤可以还原的加密来存储密码”设置为“禁⽤”“复位账户锁定计数器”设置为15分钟,贴图这里是我自己设置的时间,15分钟也够用,具体看自己需要。”网络访问: 不允许 SAM 帐户和共享的匿名枚举“设置为“已启用””网络访问: 限制对命名管道和共享的匿名访问“设置为“已启用””网络访问: 不允许匿名枚举 SAM 帐户“设置为“已启用”“关机: 允许系统在未登录的情况下关闭”设置为“已禁用”(1)交互式登录:不显示最后的⽤户名”设置为“已启⽤”

weixin_48825672的博客 3140

使用spring AOP方式对请求数据进行去空,校验。

使用spring AOP方式对请求数据进行去空,校验。 AOP是什么 我们来看百度给的解释: AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。 说人话就是: 为什么叫

weixin_43646135的博客 772

RSA算法详解:万字文章详解RSA的加密与解密

为了彻彻底底的研究明白RSA算法,真的是。。煞(lei)费(si)苦(wo)心(le),首先我希望自己前前后后、彻彻底底的琢磨明白,其次我也希望我把他分享出来以后,大家都能读得懂,这篇文章真的是我迄今为止写的又臭又长的一篇文章了,但是我能保证的是,你读完了以后,绝对不会再问RSA是啥玩意儿了。。

布啦啦 7682

MIKE水动力笔记7_实测数据与模型输出结果的拟合对比

上一博文【MIKE水动力笔记6】主要讲解如何自己制作实测数据的时间序列文件dfs0,而本博文讲解如何进行实测数据与模型输出结果的拟合对比。

晏长街的博客 1万+

Spring AOP全面详解

AOP(Aspect Orient Programming),即面向切面编程,是一种编程思想,用于在不修改源代码的情况下动态地给程序添加额外功能。它通过横向抽取机制取代了传统纵向继承机制的重复性代码,主要应用在事务处理、日志管理、权限控制等方面,分离功能性需求和非功能性需求,减少对业务代码的侵入,增强代码的可读性和可维护性。增强处理(Advice)是在AOP框架中为普通业务组件织入的处理动作。前置通知(Before):在目标方法执行前执行。后置通知。

ning的博客 1508

【AI编程】Trae 环境搭建与配置从使用到项目实战详解

Trae 环境搭建与配置从使用到项目实战详解

congge 5660

spring AOP详解

AOP(Aspect Orient Programming)是一种设计思想,是软件设计领域中的面向切面编程,它是面向对象编程(OOP)的一种补充和完善;

是程序喵呀 4214

手把手教你学Simulink实例--基于simulink搭建起一个基础的矩阵变换器仿真模型

矩阵变换器(Matrix Converter, MC)是一种直接将交流电源转换为另一频率和幅值的交流电源的电力电子设备,它不需要中间的直流环节。这种变换器通过控制一组双向开关来实现对输入电压的精确控制,从而产生所需的输出电压波形。Simulink提供了强大的仿真环境,可以用于设计、分析和验证基于矩阵变换器的电源系统。

MHD0815的博客 347

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

详解Spring AOP篇一

详解AOP及Spring AOP的使用,以及AOP面向切面编程的优势。

. 2647

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

详解Spring AOP

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

N_0050的博客 2032

深度学习工具包 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")

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

Spring AOP用法详解

AOP:Aspect Oriented Programming,中文翻译为”面向切面编程“。面向切面编程是一种编程范式,它作为OOP面向对象编程的一种补充,用于处理系统中分布于各个模块的横切关注点,比如事务管理、权限控制、缓存控制、日志打印等等。AOP采取横向抽取机制,取代了传统纵向继承体系的重复性代码

深圳市多克创新科技有限公司 1684

Spring之AOP详解

AOP介绍 AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善。 面向切面是面向对象中的一种方式而已。在代码执行过程中,动态嵌入其他代码,叫做面向切面编程。常见的使用场景: i :日志 ii: 事务 iii:数据库操作 … 面向切面编程的几个核心概念 概念 ...

波波烤鸭的博客 6652

spring aop详解

1.前言 spring aop是一个面向切面的编程,在自己第一遍学习的时候,感觉aop没有什么作用,但是真实接触下来,感觉spring aop还是很有用途的,感觉自己之前的想法太年轻了。 2.概念 Spring 提供了两种AOP 的实现:基于注解式配置和基于XML配置,我这里主要就是介绍一下,基于注解式配置。 2.1 AOP 即 Aspect Oriented Program 面向切面编程 首先,在面向切面编程的思想里面,把功能分为核心业务功能,和周边功能。 所谓的核心业务,工作中做的最多的

hanbin1998的博客 6566

【SpringBoot】Spring AOP详解

本期讲解:什么是Spring AOP,以及SpringAOP的前直通知、后置通知、返回之后通知、抛异常后通知、环绕通知。

我的主页 4392
上一篇: Spring IOC 依赖注入的两种方式:XML和注解
下一篇: 使用Spring的注解方式实现AOP
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值