读书人

Spring3.0中的AOP诠注配置

发布时间: 2012-07-05 07:59:18 作者: rapoo

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代码 Spring3.0中的AOP诠注配置
  1. import org.aspectj.lang.ProceedingJoinPoint;
  2. import org.aspectj.lang.annotation.After;
  3. import org.aspectj.lang.annotation.AfterThrowing;
  4. import org.aspectj.lang.annotation.Around;
  5. import org.aspectj.lang.annotation.Aspect;
  6. import org.aspectj.lang.annotation.Before;
  7. import org.springframework.stereotype.Component;
  8. /**
  9. * 基于注解的AOP日志示例
  10. * @author ZYWANG 2011-3-24
  11. */
  12. @Component
  13. @Aspect
  14. public class AopLog {
  15. //方法执行前调用
  16. @Before("execution (* com.zywang.services.impl.*.*(..))")
  17. public void before() {
  18. System.out.println("before");
  19. }
  20. //方法执行后调用
  21. @After("execution (* com.zywang.services.impl.*.*(..))")
  22. public void after() {
  23. System.out.println("after");
  24. }
  25. //方法执行的前后调用
  26. @Around("execution (* com.zywang.services.impl.*.*(..))")
  27. public Object around(ProceedingJoinPoint point) throws Throwable{
  28. System.out.println("begin around");
  29. Object object = point.proceed();
  30. System.out.println("end around");
  31. return object;
  32. }
  33. //方法运行出现异常时调用
  34. @AfterThrowing(pointcut = "execution (* com.zywang.services.impl.*.*(..))",throwing = "ex")
  35. public void afterThrowing(Exception ex){
  36. System.out.println("afterThrowing");
  37. System.out.println(ex);
  38. }
  39. }

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

Java代码 Spring3.0中的AOP诠注配置
  1. import org.aspectj.lang.ProceedingJoinPoint;
  2. import org.aspectj.lang.annotation.Around;
  3. import org.aspectj.lang.annotation.Aspect;
  4. import org.aspectj.lang.annotation.Before;
  5. import org.aspectj.lang.annotation.Pointcut;
  6. import org.springframework.stereotype.Component;
  7. /**
  8. * 基于注解的AOP日志示例
  9. * @author ZYWANG 2011-3-24
  10. */
  11. @Component
  12. @Aspect
  13. public class AopLog {
  14. @Pointcut("execution (* com.iflysse.school.services.impl.*.*(..))")
  15. public void pointcut(){}
  16. //方法执行前调用
  17. @Before("pointcut()")
  18. public void before() {
  19. System.out.println("before");
  20. }
  21. //方法执行的前后调用
  22. @Around("pointcut()")
  23. public Object around(ProceedingJoinPoint point) throws Throwable{
  24. System.out.println("begin around");
  25. Object object = point.proceed();
  26. System.out.println("end around");
  27. return object;
  28. }
  29. }


读书人网 >其他相关

热点推荐