Spring切面类注解

Spring 切面类注解
① 在类上使用 @Component 注解 把切面类加入到IOC容器中
② 在类上使用 @Aspect 注解 使之成为切面类


/**
 * 日志切面
 * 
 * @author zhaoshuiqing<br>
 * @date 2019年6月14日 下午3:03:29
 */
@Component
@Aspect
public class LoggingAspect {

    //现在想在实现类中的每个方法执行前、后、以及是否发生异常等信息打印出来,需要把日志信息抽取出来,写到对应的切面的类中 LoggingAspect.java 中 
    //要想把一个类变成切面类,需要两步, 
    //① 在类上使用 @Component 注解 把切面类加入到IOC容器中 
    //② 在类上使用 @Aspect 注解 使之成为切面类
    
    
    /**
     * 前置通知:目标方法执行之前执行以下方法体的内容 
     * @param jp
     */
    @Before("execution(* com.svse.aop.*.*(..))")
    public void beforeMethod(JoinPoint jp){
         String methodName =jp.getSignature().getName();
         System.out.println("【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
    }
    
     /**
     * 返回通知:目标方法正常执行完毕时执行以下代码
     * @param jp
     * @param result
     */
    @AfterReturning(value="execution(* com.svse.aop.*.*(..))",returning="result")
    public void afterReturningMethod(JoinPoint jp, Object result){
         String methodName =jp.getSignature().getName();
         System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】");
    }
    
      /**
     * 后置通知:目标方法执行之后执行以下方法体的内容,不管是否发生异常。
     * @param jp
     */
    @After("execution(* com.svse.aop.*.*(..))")
    public void afterMethod(JoinPoint jp){
        System.out.println("【后置通知】this is a afterMethod advice...");
    }
    
    

    /**
     * 异常通知:目标方法发生异常的时候执行以下代码
     */
    @AfterThrowing(value="execution(* com.qcc.beans.aop.*.*(..))",throwing="e")
    public void afterThorwingMethod(JoinPoint jp, NullPointerException e){
         String methodName = jp.getSignature().getName();
         System.out.println("【异常通知】the method 【" + methodName + "】 occurs exception: " + e);
    }
    
    
  /**
  * 环绕通知:目标方法执行前后分别执行一些代码,发生异常的时候执行另外一些代码
  * @return 
  */
 /*@Around(value="execution(* com.svse.aop.*.*(..))")
 public Object aroundMethod(ProceedingJoinPoint jp){
     String methodName = jp.getSignature().getName();
     Object result = null;
     try {
         System.out.println("【环绕通知中的--->前置通知】:the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
         //执行目标方法
         result = jp.proceed();
         System.out.println("【环绕通知中的--->返回通知】:the method 【" + methodName + "】 ends with " + result);
     } catch (Throwable e) {
         System.out.println("【环绕通知中的--->异常通知】:the method 【" + methodName + "】 occurs exception " + e);
     }
     
     System.out.println("【环绕通知中的--->后置通知】:-----------------end.----------------------");
     return result;
 }*/

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值