Spring3.0中的AOP注解配置

转自:http://zywang.iteye.com/blog/974226

使用@AspectJ标签

  1. 在配置文件中添加<aop:aspectj-autoproxy/>注解
  2. 创建一个Java文件,使用@Aspect注解修饰该类
  3. 创建一个方法,使用@Before、@After、@Around等进行修饰,在注解中写上切入点的表达式

说明:上述Java文件创建好后,需要将其在Spring的容器中进行声明,可以在配置文件中定义<bean/>节点,也可以使用@Component组件进行修饰

示例:

Java代码 收藏代码
  1. importorg.aspectj.lang.ProceedingJoinPoint;
  2. importorg.aspectj.lang.annotation.After;
  3. importorg.aspectj.lang.annotation.AfterThrowing;
  4. importorg.aspectj.lang.annotation.Around;
  5. importorg.aspectj.lang.annotation.Aspect;
  6. importorg.aspectj.lang.annotation.Before;
  7. importorg.springframework.stereotype.Component;
  8. /**
  9. *基于注解的AOP日志示例
  10. *@authorZYWANG2011-3-24
  11. */
  12. @Component
  13. @Aspect
  14. publicclassAopLog{
  15. //方法执行前调用
  16. @Before("execution(*com.zywang.services.impl.*.*(..))")
  17. publicvoidbefore(){
  18. System.out.println("before");
  19. }
  20. //方法执行后调用
  21. @After("execution(*com.zywang.services.impl.*.*(..))")
  22. publicvoidafter(){
  23. System.out.println("after");
  24. }
  25. //方法执行的前后调用
  26. @Around("execution(*com.zywang.services.impl.*.*(..))")
  27. publicObjectaround(ProceedingJoinPointpoint)throwsThrowable{
  28. System.out.println("beginaround");
  29. Objectobject=point.proceed();
  30. System.out.println("endaround");
  31. returnobject;
  32. }
  33. //方法运行出现异常时调用
  34. @AfterThrowing(pointcut="execution(*com.zywang.services.impl.*.*(..))",throwing="ex")
  35. publicvoidafterThrowing(Exceptionex){
  36. System.out.println("afterThrowing");
  37. System.out.println(ex);
  38. }
  39. }

上面这段代码中多次使用了重复的切入点,这种情况下,可以使用@Pointcut标注,来修改一个切入点方法(这个方法不需要参数和方法体),然后就可以在@Before等标注中引用该方法作为切入点,示例如下:

Java代码 收藏代码
  1. importorg.aspectj.lang.ProceedingJoinPoint;
  2. importorg.aspectj.lang.annotation.Around;
  3. importorg.aspectj.lang.annotation.Aspect;
  4. importorg.aspectj.lang.annotation.Before;
  5. importorg.aspectj.lang.annotation.Pointcut;
  6. importorg.springframework.stereotype.Component;
  7. /**
  8. *基于注解的AOP日志示例
  9. *@authorZYWANG2011-3-24
  10. */
  11. @Component
  12. @Aspect
  13. publicclassAopLog{
  14. @Pointcut("execution(*com.iflysse.school.services.impl.*.*(..))")
  15. publicvoidpointcut(){}
  16. //方法执行前调用
  17. @Before("pointcut()")
  18. publicvoidbefore(){
  19. System.out.println("before");
  20. }
  21. //方法执行的前后调用
  22. @Around("pointcut()")
  23. publicObjectaround(ProceedingJoinPointpoint)throwsThrowable{
  24. System.out.println("beginaround");
  25. Objectobject=point.proceed();
  26. System.out.println("endaround");
  27. returnobject;
  28. }
  29. }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值