一、AOP的基本概念:

  • 连接点(Jointpoint):表示需要在程序中插入横切关注点的扩展点,连接点可能是类初始化、方法执行、方法调用、字段调用或处理异常等等,Spring只支持方法执行连接点,在AOP中表示为“在哪里干”;
  • 切入点(Pointcut):选择一组相关连接点的模式,即可以认为连接点的集合,Spring支持perl5正则表达式和AspectJ切入点模式,Spring默认使用AspectJ语法,在AOP中表示为“在哪里干的集合”;
  • 通知(Advice):在连接点上执行的行为,通知提供了在AOP中需要在切入点所选择的连接点处进行扩展现有行为的手段;包括前置通知(before advice)、后置通知(after advice)、环绕通知(around advice),在Spring中通过代理模式实现AOP,并通过拦截器模式以环绕连接点的拦截器链织入通知;在AOP中表示为“干什么”;
    • 前置通知(Before Advice):在切入点选择的连接点处的方法之前执行的通知,该通知不影响正常程序执行流程(除非该通知抛出异常,该异常将中断当前方法链的执行而返回);
    • 环绕通知(Around Advices):环绕着在切入点选择的连接点处的方法所执行的通知,环绕通知可以在方法调用之前和之后自定义任何行为,并且可以决定是否执行连接点处的方法、替换返回值、抛出异常等等。
    • 后置通知(After Advice):在切入点选择的连接点处的方法之后执行的通知,包括如下类型的后置通知:
      • 后置返回通知(After returning Advice):在切入点选择的连接点处的方法正常执行完毕时执行的通知,必须是连接点处的方法没抛出任何异常正常返回时才调用后置通知。
      • 后置异常通知(After throwing Advice): 在切入点选择的连接点处的方法抛出异常返回时执行的通知,必须是连接点处的方法抛出任何异常返回时才调用异常通知。
      • 后置最终通知(After finally Advice): 在切入点选择的连接点处的方法返回时执行的通知,不管抛没抛出异常都执行,类似于Java中的finally块。
  • 方面/切面(Aspect):横切关注点的模块化,比如上边提到的日志组件。可以认为是通知、引入和切入点的组合;在Spring中可以使用Schema和@AspectJ方式进行组织实现;在AOP中表示为“在哪干和干什么集合”;
  • 引入(inter-type declaration):也称为内部类型声明,为已有的类添加额外新的字段或方法,Spring允许引入新的接口(必须对应一个实现)到所有被代理对象(目标对象), 在AOP中表示为“干什么(引入什么)”;
  • 目标对象(Target Object):需要被织入横切关注点的对象,即该对象是切入点选择的对象,需要被通知的对象,从而也可称为“被通知对象”;由于Spring AOP 通过代理模式实现,从而这个对象永远是被代理对象,在AOP中表示为“对谁干”;
  • AOP代理(AOP Proxy):AOP框架使用代理模式创建的对象,从而实现在连接点处插入通知(即应用切面),就是通过代理来对目标对象应用切面。在Spring中,AOP代理可以用JDK动态代理或CGLIB代理实现,而通过拦截器模型应用切面。
  • 织入(Weaving):织入是一个过程,是将切面应用到目标对象从而创建出AOP代理对象的过程,织入可以在编译期、类装载期、运行期进行。

注解形式:

步骤一、定义一个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;
} }

步骤四、Spring的配置文件中使用aop命名空间

<?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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
default-autowire="byName" default-lazy-init="false">
<!--
自动为Spring容器中那些匹配@AspectJ切面的Bean创建代理,完成切面织入。
proxy-target-class属性,默认是false,表示使用JDK动态代理技术织入增强。
当设置为true时,表示使用CGLib动态代理技术织入增强。不过即使设置为false,
如果目标类没有实现接口,则Spring将自动使用CGLib动态代理
-->
<aop:aspectj-autoproxy proxy-target-class="false"/>
</beans>

步骤五、测试

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简单入门的更多相关文章

  1. 用IntelliJ IDEA创建Gradle项目简单入门

    Gradle和Maven一样,是Java用得最多的构建工具之一,在Maven之前,解决jar包引用的问题真是令人抓狂,有了Maven后日子就好过起来了,而现在又有了Gradle,Maven有的功能它都 ...

  2. [原创]MYSQL的简单入门

    MYSQL简单入门: 查询库名称:show databases; information_schema mysql test 2:创建库 create database 库名 DEFAULT CHAR ...

  3. Okio 1.9简单入门

    Okio 1.9简单入门 Okio库是由square公司开发的,补充了java.io和java.nio的不足,更加方便,快速的访问.存储和处理你的数据.而OkHttp的底层也使用该库作为支持. 该库极 ...

  4. emacs最简单入门,只要10分钟

    macs最简单入门,只要10分钟  windwiny @2013    无聊的时候又看到鼓吹emacs的文章,以前也有几次想尝试,结果都是玩不到10分钟就退出删除了. 这次硬着头皮,打开几篇文章都看完 ...

  5. 【java开发系列】—— spring简单入门示例

    1 JDK安装 2 Struts2简单入门示例 前言 作为入门级的记录帖,没有过多的技术含量,简单的搭建配置框架而已.这次讲到spring,这个应该是SSH中的重量级框架,它主要包含两个内容:控制反转 ...

  6. Docker 简单入门

    Docker 简单入门 http://blog.csdn.net/samxx8/article/details/38946737

  7. Springmvc整合tiles框架简单入门示例(maven)

    Springmvc整合tiles框架简单入门示例(maven) 本教程基于Springmvc,spring mvc和maven怎么弄就不具体说了,这边就只简单说tiles框架的整合. 先贴上源码(免积 ...

  8. git简单入门

    git简单入门 标签(空格分隔): git git是作为程序员必备的技能.在这里就不去介绍版本控制和git产生的历史了. 首先看看常用的git命令: git init git add git comm ...

  9. 程序员,一起玩转GitHub版本控制,超简单入门教程 干货2

    本GitHub教程旨在能够帮助大家快速入门学习使用GitHub,进行版本控制.帮助大家摆脱命令行工具,简单快速的使用GitHub. 做全栈攻城狮-写代码也要读书,爱全栈,更爱生活. 更多原创教程请关注 ...

随机推荐

  1. Nginx中并发性能相关配置参数说明

    worker_processes:开启worker进程的数目,通常可设置为CPU核心的倍数.在不清楚的情况下,可设置成一倍于CPU核心数或auto(Nginx将自动发现CPU核心数). worker_ ...

  2. css多重边框

    一.使用box-shadow实现多重边框 html <div class="multiple"></div> css .multiple{ backgrou ...

  3. mysql之其他

    一 IDE工具介绍 下载链接:https://pan.baidu.com/s/1bpo5mqj 掌握: 1. 测试+链接数据库 2. 新建库 3. 新建表,新增字段+类型+约束 4. 设计表:外键 5 ...

  4. K:图相关的最小生成树(MST)

    相关介绍:  根据树的特性可知,连通图的生成树是图的极小连通子图,它包含图中的全部顶点,但只有构成一棵树的边:生成树又是图的极大无回路子图,它的边集是关联图中的所有顶点而又没有形成回路的边.  一个有 ...

  5. 8、ABPZero系列教程之拼多多卖家工具 添加手机注册登录功能

    现在网站基本都用手机注册,很少用邮箱注册,本篇内容比较多,代码我会尽量加备注,有些操作需要连续添加几个文件才不报错,如果VS显示错误,请继续后续步骤. 前面已经有一篇文章讲到集成短信发送模块:http ...

  6. Python面试题解答

    1. 一个谜题 >>> t = (1, 2, [30, 40]) >>> t[2] += [50, 60] 到底会发生下面 4 种情况中的哪一种? a. t变成(1 ...

  7. python 虚拟环境--virtualenv

    virtualenv 是一个创建隔绝的Python环境的工具.virtualenv创建一个包含所有必要的可执行文件的文件夹,用来使用Python工程所需的包. 安装方式一: pip install v ...

  8. 牛客网linux试题-错误整理-20171013

    创建对象时,对象的内存和指向对象的指针分别分配在:堆区,栈区 堆内存用来存放由new创建的对象和数组,在堆中产生了一个数组或对象后,还可以在栈中定义一个特殊的变量,让栈中这个变量的取值等于数组或对象在 ...

  9. C# 实现邮件发送

    要实现邮件发送功能首先需要准备两三个邮箱测试,在这里呢准备了2个QQ邮箱和一个微软邮箱,详细请看代码. 我这里是使用QQ邮箱向另外两个邮箱发送邮件的,在开始写代码之前你需要登录你QQ邮箱进行以下几个操 ...

  10. django笔记整理

    Django复习: MTV模型: manager启动服务→urls找到路径→(找到views视图函数或者做路由分发)→视图函数处理相关逻辑,返回一个模板或者是字符串: ---------------- ...