在spring中有两种增强方式:XML配置文件和注解配置。下面一次为大家讲解。

  使用的是Aspectj第三方框架 纯POJO (在XML中配置节点)

   spring中的增强类型

 

  使用@AspectJ,首先要保证所用的JDK 是5.0或以上版本

 

  1)首先,创建一个切入点MyAspect,代码如下:

 1 public class MyAspect {
 2     // 前置通知
 3     public void myBefore() {
 4         System.out.println("这是前置增强");
 5     }
 6     //前置通知带参
 7     public void before(JoinPoint jp) {
 8         System.out.println("前置通知方法before() jp = " + jp);
 9     }
10 
11     // 后置通知
12     public void myAfterReturning() {
13         System.out.println("这是后置增强");
14     }
15 
16     // 后置通知带参
17     public void afterReturing(String result) {
18         System.out.println("后置通知方法 result = " + result);
19     }
20 
21     // 环绕通知
22     public Object around(ProceedingJoinPoint pjp) throws Throwable {
23         System.out.println("环绕通知方法,目标方法执行之前");
24         // 执行目标方法
25         Object result = pjp.proceed();
26         System.out.println("环绕通知方法,目标方法执行之后");
27         return ((String) result).toUpperCase();
28     }
29 
30     // 异常通知
31     public void afterThrowing() {
32         System.out.println("异常通知方法");
33     }
34 
35     public void afterThrowing(Exception ex) {
36         System.out.println("异常通知方法 ex = " + ex.getMessage());
37     }
38 
39     // 最终通知
40     public void after() {
41         System.out.println("最终通知方法");
42     }
43 }
通知(MyAspect.java)

相关文章: