Spring_17-19前置通知&后置通知&返回通知&异常通知&环绕通知

  • ArithmeticCalculator
package com.hgh.spring.aop.annotation;

public interface ArithmeticCalculator {

    int add(int i,int j);
    int sub(int i,int j);
    int div(int i,int j);
}
  • ArithmeticCalculatorImpl
package com.hgh.spring.aop.annotation;

import org.springframework.stereotype.Component;

@Component("ArithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator{

    @Override
    public int add(int i, int j) {
        // TODO Auto-generated method stub
        return i+j;
    }

    @Override
    public int sub(int i, int j) {
        // TODO Auto-generated method stub
        return i-j;
    }

    @Override
    public int div(int i, int j) {
        // TODO Auto-generated method stub
        return i/j;
    }

}
  • LoggingAspect
package com.hgh.spring.aop.annotation;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

//声明为切面
@Aspect
@Component
public class LoggingAspect {
    /**
     * 定义一个方法, 用于声明切入点表达式. 一般地, 该方法中再不需要添入其他的代码. 
     * 使用 @Pointcut 来声明切入点表达式. 
     * 后面的其他通知直接使用方法名来引用当前的切入点表达式. 
     */
    @Pointcut("execution(* com.hgh.spring.aop.annotation.ArithmeticCalculator.*(..))")
    public void loggingPointcut(){}

    //前置通知
    //@Before("execution(public int com.hgh.spring.aop.annotation.ArithmeticCalculator.*(..))")
    @Before("loggingPointcut()")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("the method "+methodName+"Before with"+Arrays.asList(args));
    }
    /**
     * 在方法执行之后执行的代码. 无论该方法是否出现异常
     */
    @After("loggingPointcut()")
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("the method "+methodName+" After with");
    }
    /**
     * 在方法法正常结束受执行的代码
     * 返回通知是可以访问到方法的返回值的!
     */
    @AfterReturning(value="loggingPointcut()",returning="result")
    public void returningMethod(JoinPoint joinPoint,Object result){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("the method "+methodName+" AfterReturning with "+result);
    }
    /**
     * 在目标方法出现异常时会执行的代码.
     * 可以访问到异常对象; 且可以指定在出现特定异常时在执行通知代码
     */
    @AfterThrowing(value="loggingPointcut()",throwing="e")
    public void throwingMethod(JoinPoint joinPoint ,Exception e){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("the method "+methodName+" throwingMethod with exception:"+e.getMessage());
    }
    /**
     * 环绕通知需要携带 ProceedingJoinPoint 类型的参数. 
     * 环绕通知类似于动态代理的全过程: ProceedingJoinPoint 类型的参数可以决定是否执行目标方法.
     * 且环绕通知必须有返回值, 返回值即为目标方法的返回值
     */
    @Around(value="loggingPointcut()")
    public Object aroudMethod(ProceedingJoinPoint proceedingJoinPoint){
        String methodName = proceedingJoinPoint.getSignature().getName();
        Object result = null;
        try {
            //前置通知
            System.out.println("The method " + methodName + " begins with " + Arrays.asList(proceedingJoinPoint.getArgs()));
            //执行目标方法
            result = proceedingJoinPoint.proceed();
            //返回通知
            System.out.println("The method " + methodName + " ends with " + result);
        } catch (Throwable e) {
            //异常通知
            System.out.println("The method " + methodName + " occurs exception:" + e);
            throw new RuntimeException(e);
        }
        //后置通知
        System.out.println("The method " + methodName + " ends");

        return result;
    }

}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.hgh.spring.aop.annotation"></context:component-scan>

<!-- 配置aspect切面 -->
<!-- 配置自动为匹配 aspectJ 注解的 Java 类生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
  • 测试类
package com.hgh.spring.aop.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

        //得用spring管理的那个,不能自己new
        //ArithmeticCalculatorImpl arithmeticCalculator = new ArithmeticCalculatorImpl();
        ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ac.getBean("ArithmeticCalculator");
        System.out.println(arithmeticCalculator.getClass().getName());
        int result = arithmeticCalculator.add(10, 5);
        System.out.println(result);
        result = arithmeticCalculator.div(100, 0);
//      com.sun.proxy.$Proxy7
//      the method addBefore with[10, 5]
//      15

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值