最近遇到回调函数问题,有点不太理解,到底什么是回调函数,有何用途,与命令模式是不是有点关系!
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 matlab(相关搜索:紧聚焦)
- ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
- ¥15 路易威登官网 里边的参数逆向
- ¥15 Arduino无法同时连接多个hx711模块,如何解决?
- ¥50 需求一个up主付费课程
- ¥20 模型在y分布之外的数据上预测能力不好如何解决
- ¥15 processing提取音乐节奏
- ¥15 gg加速器加速游戏时,提示不是x86架构
- ¥15 python按要求编写程序
- ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入