AOP中的@Aspect用法,用于监控程序的执行方法

来源:互联网 发布:算法导论吃透后的水平 编辑:程序博客网 时间:2024/06/06 00:51

Spring使用的AOP注解分为三个层次:

前提条件是在xml中放开了<aop:aspectj-autoproxy proxy-target-class="true"/><!-- 开启切面编程功能 -->

1、@Aspect放在类头上,把这个类作为一个切面。

2、 @Pointcut放在方法头上,定义一个可被别的方法引用的切入点表达式。

3、5种通知。

3.1、@Before,前置通知,放在方法头上。

3.2、@After,后置【finally】通知,放在方法头上。

3.3、@AfterReturning,后置【try】通知,放在方法头上,使用returning来引用方法返回值。

3.4、@AfterThrowing,后置【catch】通知,放在方法头上,使用throwing来引用抛出的异常。

3.5、@Around,环绕通知,放在方法头上,这个方法要决定真实的方法是否执行,而且必须有返回值。

Java代码  收藏代码
  1. @Component  
  2. @Aspect  
  3. public class LogAspect {  
  4.   
  5.     /** 
  6.      * 定义Pointcut,Pointcut的名称 就是simplePointcut,此方法不能有返回值,该方法只是一个标示 
  7.      */  
  8.     @Pointcut("execution(public * com.service.impl..*.*(..))")  
  9.     public void recordLog() {  
  10.     }  
  11.   
  12.     @AfterReturning(pointcut = "recordLog()")  
  13.     public void simpleAdvice() {  
  14.         LogUtil.info("AOP后处理成功 ");  
  15.     }  
  16.   
  17.     @Around("recordLog()")  
  18.     public Object aroundLogCalls(ProceedingJoinPoint jp) throws Throwable {  
  19.         LogUtil.info("正常运行");  
  20.         return jp.proceed();  
  21.     }  
  22.   
  23.     @Before("recordLog()")  
  24.     public void before(JoinPoint jp) {  
  25.         String className = jp.getThis().toString();  
  26.         String methodName = jp.getSignature().getName(); // 获得方法名  
  27.         LogUtil.info("位于:" + className + "调用" + methodName + "()方法-开始!");  
  28.         Object[] args = jp.getArgs(); // 获得参数列表  
  29.         if (args.length <= 0) {  
  30.             LogUtil.info("====" + methodName + "方法没有参数");  
  31.         } else {  
  32.             for (int i = 0; i < args.length; i++) {  
  33.                 LogUtil.info("====参数  " + (i + 1) + ":" + args[i]);  
  34.             }  
  35.         }  
  36.         LogUtil.info("=====================================");  
  37.     }  
  38.   
  39.     @AfterThrowing("recordLog()")  
  40.     public void catchInfo() {  
  41.         LogUtil.info("异常信息");  
  42.     }  
  43.   
  44.     @After("recordLog()")  
  45.     public void after(JoinPoint jp) {  
  46.         LogUtil.info("" + jp.getSignature().getName() + "()方法-结束!");  
  47.         LogUtil.info("=====================================");  
  48.     }  
  49. }  
0 0
原创粉丝点击