Spring的5种通知

摘要:
1.前置通知BeforeadviceAdvicethatexecutesbeforeajoinpoint,butwhichdoesnothavetheabilitytopreventexecutionflowproceedingtothejoinpoint(unlessitthrowsanexception).2.后置通知After(finally)adviceAdvicetobeexecuted

1.前置通知 Before advice

Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).

2.后置通知 After (finally) advice

Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).

3.返回通知 After returningadvice

Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.

4.异常通知 After throwing advice

Advice to be executed if a method exits by throwing an exception.

5.环绕通知 Around advice

Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

一.前置通知

Before advice is declared in an aspect using the@Beforeannotation:

1 importorg.aspectj.lang.annotation.Aspect;
2 importorg.aspectj.lang.annotation.Before;
3 
4 @Aspect
5 public classBeforeExample {
6 
7     @Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
8     public voiddoAccessCheck() {
9         //...
10 }
11 
12 }

If using an in-place pointcut expression we could rewrite the above example as:

1 importorg.aspectj.lang.annotation.Aspect;
2 importorg.aspectj.lang.annotation.Before;
3 
4 @Aspect
5 public classBeforeExample {
6 
7     @Before("execution(* com.xyz.myapp.dao.*.*(..))")
8     public voiddoAccessCheck() {
9         //...
10 }
11 
12 }

二.后置通知

After (finally) advice runs however a matched method execution exits. It is declared using the@Afterannotation. After advice must be prepared to handle both normal and exception return conditions. It is typically used for releasing resources, etc.

importorg.aspectj.lang.annotation.Aspect;
importorg.aspectj.lang.annotation.After;

@Aspect
public classAfterFinallyExample {

    @After("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
    public voiddoReleaseLock() {
        //...
}

}

三.返回通知

After returning advice runs when a matched method execution returns normally. It is declared using the@AfterReturningannotation:

importorg.aspectj.lang.annotation.Aspect;
importorg.aspectj.lang.annotation.AfterReturning;

@Aspect
public classAfterReturningExample {

    @AfterReturning("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
    public voiddoAccessCheck() {
        //...
}

}

Sometimes you need access in the advice body to the actual value that was returned. You can use the form of@AfterReturningthat binds the return value for this:

1 importorg.aspectj.lang.annotation.Aspect;
2 importorg.aspectj.lang.annotation.AfterReturning;
3 
4 @Aspect
5 public classAfterReturningExample {
6 
7 @AfterReturning(
8         pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()",
9         returning="retVal")
10     public voiddoAccessCheck(Object retVal) {
11         //...
12 }
13 
14 }

四.异常通知

After throwing advice runs when a matched method execution exits by throwing an exception. It is declared using the@AfterThrowingannotation:

importorg.aspectj.lang.annotation.Aspect;
importorg.aspectj.lang.annotation.AfterThrowing;

@Aspect
public classAfterThrowingExample {

    @AfterThrowing("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
    public voiddoRecoveryActions() {
        //...
}

}

Often you want the advice to run only when exceptions of a given type are thrown, and you also often need access to the thrown exception in the advice body. Use thethrowingattribute to both restrict matching (if desired, useThrowableas the exception type otherwise) and bind the thrown exception to an advice parameter.

importorg.aspectj.lang.annotation.Aspect;
importorg.aspectj.lang.annotation.AfterThrowing;

@Aspect
public classAfterThrowingExample {

    @AfterThrowing(
        pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()",
        throwing="ex")
    public voiddoRecoveryActions(DataAccessException ex) {
        //...
}

}

五.环绕通知

The final kind of advice is around advice. Around advice runs "around" a matched method execution. It has the opportunity to do work both before and after the method executes, and to determine when, how, and even if, the method actually gets to execute at all. Around advice is often used if you need to share state before and after a method execution in a thread-safe manner (starting and stopping a timer for example). Always use the least powerful form of advice that meets your requirements (i.e. don’t use around advice if simple before advice would do).

Around advice is declared using the@Aroundannotation. The first parameter of the advice method must be of typeProceedingJoinPoint. Within the body of the advice, callingproceed()on theProceedingJoinPointcauses the underlying method to execute. Theproceedmethod may also be called passing in anObject[]- the values in the array will be used as the arguments to the method execution when it proceeds.

importorg.aspectj.lang.annotation.Aspect;
importorg.aspectj.lang.annotation.Around;
importorg.aspectj.lang.ProceedingJoinPoint;

@Aspect
public classAroundExample {

    @Around("com.xyz.myapp.SystemArchitecture.businessService()")
    public Object doBasicProfiling(ProceedingJoinPoint pjp) throwsThrowable {
        //start stopwatch
        Object retVal =pjp.proceed();
        //stop stopwatch
        returnretVal;
    }

}

免责声明:文章转载自《Spring的5种通知》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Fastjson介绍Ansible主机清单Inventory文件hosts下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

WebStorm好用的插件推荐

随着时间的推移,编写JavaScript代码很多有用的插件都集成了WebStorm中,在WebStorm中即使不装任何插件,都能很舒服的进行开发网页应用、Node应用。插件对于WebStorm并不是特别的重要,但是某些插件实在是比较好用,所以本篇文章就整理一下比较好用的插件。使用该插件,可以直接在WebStorm中内嵌一个翻译界面。...

Zabbix故障处理系列

然后,您还需要重新启动zabbix porxy。我刚重启了zabbix特工。然而,Zabbix网络界面的图形中没有数据。此时,重新启动zabbix代理以解决相应的问题。Zbx在Zabbix监控的网页上也显示为灰色。有时,其中一些可能是绿色的,如下所示:问题2:当Zabbix代理未升级时,无法在Zabbix监控页面上监控数据。原因:ZABBIX4.0版本存在兼...

将Kafka收到的数据传入到redis中

首先,配置配置。在属性测试中,首先启动网络管理系统(GateWay),然后启动终端(TBox),然后运行KafkaTest启动TBox。在启动测试中可以看到收到的数据。然后关键是sdf,然后去你的xshell启动动物园管理员、kafka和redis...

浪潮各机型管理芯片BMC IP(智能平台管理接口)设置

NF5240m3/NF5140m3/NF5280m3/SA5212H2/NP5540M3NF5270M3/NF5170M3/NF8420m3IPMI主板集成管理芯片BMCIP设置开机按DEL键进入BIOS设置选择"ServerMgmt"---"BMCNetworkConfiguration"---"lanchannel1/2"---"staticipaddr...

Debian忘记密码重置

我使用的系统是Debian8,但这种方法也适用于Debian7以上的系统。具体步骤是重新启动VPS。您可以使用“CTRL+ALT+DEL”按钮直接在面板或VNC上重新启动VPS,然后按图中的“e”按钮;在BIOS界面上,按“e”进入GRUB引导菜单,然后按“e”进入编辑;输入GRUB编辑红色框中的内容,并将“ro”替换为“rwinit=/bin/sh”;修改...

allure报告实现保存失败用例截图功能

allure中可以保存日志信息和截图日志allure能够自动识别。截图需要自己在添加allure方法。...