最近遇到回调函数问题,有点不太理解,到底什么是回调函数,有何用途,与命令模式是不是有点关系!
1条回答 默认 最新
- xiaoyuebata 2010-11-27 20:35关注
是可以这样说的·这个在spring中尤其明显,比如spring中的运用到的AOP2.0以后的框架,在spring配置文件中引入aop2.0以后的命名空间后可以这样配置:
[code="java"]<?xml version="1.0" encoding="UTF-8"?>
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.0.xsd"><bean id="actor" class="aop.v2.first.Actor"/> <bean id="audience" class="aop.v2.first.Audience"></bean> <bean id="log" class="aop.v2.first.Log"></bean> <bean id="time" class="aop.v2.first.Time"></bean> <aop:config> <aop:pointcut id="pc" expression="within(aop.v2.first.Actor)"/> <aop:pointcut id="logpc" expression="within(aop.v2.first.Actor) or within(aop.v2.first.Audience)"/> <aop:pointcut id="pc1" expression="within(aop.v2.first.Actor) and args(aa,bb)"/> <aop:aspect ref="audience"> <aop:before method="takeseat" pointcut-ref="pc" /> <aop:after-returning method="applaud" pointcut-ref="pc"/> <aop:after-throwing method="protest" pointcut-ref="pc"/> </aop:aspect> <aop:aspect ref="log"> <aop:before method="before" pointcut-ref="pc"/> <aop:after-returning returning="res" method="afterReturning" pointcut-ref="pc"/> <aop:after-throwing throwing="e" method="afterThrowing" pointcut-ref="pc"/> <aop:after-throwing throwing="e" method="throwsLog" pointcut-ref="pc"/> <aop:before method="logArgs" pointcut-ref="pc1"/> </aop:aspect> <aop:aspect ref="time"> <aop:around method="around" pointcut-ref="logpc"/> </aop:aspect> </aop:config>
[/code]
其中
aop:after:等价于try-catch-finally中的finally,只要方法执行一定会执行after对应的方法
aop:around:允许多线程并发访问,Object *(ProceedingJoinPoint jp)throws Throwable{}返回值必须是Object,方法参数必须是ProceedingJoinPoint,必须抛出Throwable,三者缺一不可,JP指被拦截的目标方法(spring只支持方法)相关信息aop:after-returning:返回值之后执行的方法
aop:after-throwing:抛出异常之后执行的方法
aop:before:在调用方法之前执行的代码
这些标签对应的method属性的值就是对应定义的切面中的方法,可以在特定的情况下执行这些方法。
注意以上五个时机其实只有around是一个拦截器,他可以决定方法是否执行,其他的四种时机其实确切来说只是一个回调函数而已,除了抛出异常,否则不能终止程序的运行总得来说,回调函数就是基本的业务逻辑处理完毕之后,想增加一下额外的功能(日志的记录)或者检测(是否有异常抛出)等功能,然后程序执行的一个或多个方法
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决评论 打赏 举报无用 1
悬赏问题
- ¥15 求解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
- ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
- ¥50 树莓派安卓APK系统签名
- ¥15 maple软件,用solve求反函数出现rootof,怎么办?
- ¥65 汇编语言除法溢出问题
- ¥15 Visual Studio问题
- ¥20 求一个html代码,有偿
- ¥100 关于使用MATLAB中copularnd函数的问题
- ¥20 在虚拟机的pycharm上
- ¥15 jupyterthemes 设置完毕后没有效果