码迷,mamicode.com
首页 > 编程语言 > 详细

SpringAOP简单入门

时间:2017-12-11 16:14:47      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:div   对象   err   signature   XML   pat   通知   oid   context   

注解形式

步骤一、定义一个interface

public interface ArithmeticCalculator {
    double plus(int i, int j);
    double sub(int i, int j);
    double multi(int i, int j);
    double div(int i, int j);
}

 

步骤二、实现上面的接口

import org.springframework.stereotype.Component;

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

    public double plus(int i, int j) {
        double result = i + j;
        return result;
    }

    public double sub(int i, int j) {
        double result = i - j;
        return  result;
    }

    public double multi(int i, int j) {
        double result = i * j;
        return result;

    }

    public double div(int i, int j) {
        double result = i / j;
        return result;

    }
}

 

步骤三、写切面类

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

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

    /**
     * 前置通知
     * 在 com.atguigu.spring.aop.ArithmeticCalculator
     * 接口的每一个实现类的每一个方法开始之前执行一段代码
     * 用通配符*来表示所有
     */
//    @Before("execution(public double com.spring2.lee.aop.impl.ArithmeticCalculator.plus(int, int))")
    @Before("declareJointPointExpression()")
    public void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("before method " + methodName + " begin with:" + Arrays.asList(args));
    }

    /**
     * 后置通知
     * 在方法执行之后执行的代码. 无论该方法是否出现异常
     * @param joinPoint
     */

    @After("execution(public double com.spring2.lee.aop.impl.*.*(..))")
    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("after method " + methodName + 
                       " end " + Arrays.asList(args));
    }

    /**
     * 返回通知
     * 在方法法正常结束受执行的代码
     * 返回通知是可以访问到方法的返回值的!
     */
    @AfterReturning(value = "execution(public double com.spring2.lee.aop.impl.*.*(..))",
            returning = "result")
    public void afterReturning(JoinPoint joinPoint, 
       Object result) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + 
           " ends with " + result);
    }

    /**
     * 异常通知
     * 在目标方法出现异常时会执行的代码.
     * 可以访问到异常对象; 且可以指定在出现特定异常时在执行通知代码
     */
    @AfterThrowing(value = "execution(public double com.spring2.lee.aop.impl.*.*(..))", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + 
        " occurs excetion:" + e);
    }

    /**
     * 环绕通知需要携带 ProceedingJoinPoint 类型的参数.
     * 环绕通知类似于动态代理的全过程: ProceedingJoinPoint 类型的参数可以决定是否执行目标方法.
     * 且环绕通知必须有返回值, 返回值即为目标方法的返回值
     */
    @Around("execution(public double com.spring2.lee.aop.impl.*.*(..))")
    public Object aroundMethod(ProceedingJoinPoint pjd) {

        Object result = null;
        String methodName = pjd.getSignature().getName();

        try {
            //前置通知
            System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));
            //执行目标方法
            result = pjd.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;
    }

}

 

步骤四、测试

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

public class MainTest {
    public static void main(String[] args) {
        //1.创建Spring 的IOC 容器
        ApplicationContext application = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2. 从IOC 容器中获取bean 的实例
        ArithmeticCalculator arithmeticCalculator = application.getBean(ArithmeticCalculator.class);
        double result = arithmeticCalculator.div(2,2);
        //System.out.println("result:" + result);
    }
}

 

用xml配置的方式实现AOP

Java代码跟上面的一样,只不过注解都没有了,都是用xml来配置bean,所以只粘贴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">

       <!-- 配置 bean -->
       <bean id="arithmeticCalculator"
             class="com.spring2.lee.aop.impl.ArithmeticCalculatorImpl"></bean>
       <!-- 配置切面的 bean. -->
       <bean id="loggingAspect"
             class="com.spring2.lee.aop.impl.LoggingAspect"></bean>
       <bean id="vlidationAspect"
             class="com.spring2.lee.aop.impl.VlidationAspect"></bean>
       <!-- 配置 AOP -->
       <aop:config>
              <!-- 配置切点表达式 -->
              <aop:pointcut id="pointcut" expression="execution(* com.spring2.lee.aop.impl.ArithmeticCalculator.*(int, int))"/>
              <!-- 配置切面及通知 -->
              <aop:aspect ref="loggingAspect" order="2">
                     <aop:before method="beforeMethod" pointcut-ref="pointcut"/>
                     <aop:after method="afterMethod" pointcut-ref="pointcut"/>
                     <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>
                     <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
                     <!--
                         <aop:around method="aroundMethod" pointcut-ref="pointcut"/>
                   -->
              </aop:aspect>
              <aop:aspect ref="vlidationAspect" order="1">
                     <aop:before method="validateArgs" pointcut-ref="pointcut"/>
              </aop:aspect>
       </aop:config>
       

</beans>

 

SpringAOP简单入门

标签:div   对象   err   signature   XML   pat   通知   oid   context   

原文地址:http://www.cnblogs.com/happyflyingpig/p/8023148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!