一、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-基于@AspectJ的简单入门的更多相关文章

  1. [Spring框架]Spring AOP基础入门总结二:Spring基于AspectJ的AOP的开发.

    前言: 在上一篇中: [Spring框架]Spring AOP基础入门总结一. 中 我们已经知道了一个Spring AOP程序是如何开发的, 在这里呢我们将基于AspectJ来进行AOP 的总结和学习 ...

  2. Spring Aop(二)——基于Aspectj注解的Spring Aop简单实现

    转发地址:https://www.iteye.com/blog/elim-2394762 2 基于Aspectj注解的Spring Aop简单实现 Spring Aop是基于Aop框架Aspectj实 ...

  3. spring-AOP框架(基于AspectJ注解配置AOP)

    基于AspectJ注解配置AOP 1.加入jar包: 要在Spring应用中使用AspectJ注解,必须在classpath下包含AspectJ类库:aopalliance.jar.aspectj.w ...

  4. Spring学习之旅(七)基于XML配置与基于AspectJ注解配置的AOP编程比较

    本篇博文用一个稍复杂点的案例来对比一下基于XML配置与基于AspectJ注解配置的AOP编程的不同. 相关引入包等Spring  AOP编程准备,请参考小编的其他博文,这里不再赘述. 案例要求: 写一 ...

  5. Spring_AOP基于AspectJ的注解开发&JDBC的模板使用&事务管理(学习笔记3)

    一:AOP基于AspectJ的注解开发 1,简单的实例: 1)引入相应的jar包 ​ 2)在配置文件里引入相关约束 <beans xmlns="http://www.springfra ...

  6. 转-springAOP基于XML配置文件方式

    springAOP基于XML配置文件方式 时间 2014-03-28 20:11:12  CSDN博客 原文  http://blog.csdn.net/yantingmei/article/deta ...

  7. 基于java的设计模式入门(1)——为什么要学习设计模式

    大年初一,楼主在这里给大家拜年,祝大家码上升职加薪,码上有对象结婚,码上有车有房,幸福安康. 过完年,回学校注册报道之后,大概就要回深圳到公司开始实习了.提高自己,无非就有两种方式,一是看书学习,二是 ...

  8. 基于@AspectJ配置Spring AOP之一--转

    原文地址:http://tech.it168.com/j/2007-08-30/200708302209432.shtml 概述 在低版本Spring中定义一个切面是比较麻烦的,需要实现特定的接口,并 ...

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

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

随机推荐

  1. linux常见命令整理

    Linux管理文件和目录的命令 命令 功能 命令 功能 pwd 显示当前目录 ls 查看目录下的内容 cd 改变所在目录 cat 显示文件的内容 grep 在文件中查找某字符 cp 复制文件 touc ...

  2. Android 3D游戏开发

    OpenGL ES(OpenGL Embedded System) Android 3D游戏开发技术宝典:OpenGL ES 2.0(android 3d游戏开发技术宝典 -opengl es 2.0 ...

  3. (字符串处理)Fang Fang -- hdu -- 5455 (2015 ACM/ICPC Asia Regional Shenyang Online)

    链接: http://acm.hdu.edu.cn/showproblem.php?pid=5455 Fang Fang Time Limit: 1500/1000 MS (Java/Others)  ...

  4. web问题

    模拟form提交过程中form(hidden)时:The frame requesting access has a protocol of "http", the frame b ...

  5. Win10下安装msi程序包时报2503、2502错误问题及其解决办法

    Win10系统下安装TortoiseSvn.Node.js时(.msi后缀的安装文件),在点击安装时老是提示2503,2502错误,因此无法安装上. 搜索了下一般都提到是权限不够引起的该问题.但是右键 ...

  6. 查看sql server数据库连接数的三种方法

    怎样才能查看sql server数据库连接数呢?下面就将为您介绍三种查看的方法,供您参考,希望能够帮助到您. 1.通过系统的“性能”来查看:开始->管理工具->性能(或者是运行里面输入 m ...

  7. Easy Ui 的reload 问题

    当我删除某条数据时,删除成功后要刷新datagrid 这时调用reload方法就不成功,而要用下面的方式. 正确代码$('#fixedGrid').datagrid("reload" ...

  8. 【实战TFS】【QQ群】了解别人是如何使用TFS的

    长时间在这个QQ群里面混,了解到其他人是如何使用TFS系统的,也与网友们一起探讨,共同提高,还有分享的大量资料文档. 推荐一下:):)

  9. C#构造方法(函数)

    一.概括 1.通常创建一个对象的方法如图: 通过  Student tom = new Student(); 创建tom对象,这种创建实例的形式被称为构造方法. 简述:用来初始化对象的,为类的成员赋值 ...

  10. 如何使用socket进行java网络编程(三)

    本篇文章继续记录java网络通讯编程的学习.在本系列笔记的第一篇中曾经记录过一个项目中的程序,当时还处于项目早期,还未进入与第三方公司的联调阶段,笔者只是用java写了一个client程序模拟了一下第 ...