一、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. Vue组件通信父传方法给子组件调用

    // 父组件中将 :meth='changeCom1' 传入入子组件 , 子组件运行 meth(i) 方法 并给他传参数 ,在父组件可以获取这个参数,并做相应的操作   // 父组件 <temp ...

  2. Java_得到GET和POST请求URL和参数列表

    一. 获取URL: getRequestURL()(还有个getRequestURI(),只取后面部分) 二. 获取参数列表: 1.getQueryString() 只适用于GET,比如客户端发送ht ...

  3. C++中的浮点数运算的误差测试分析

    C++中的浮点数运算的误差 项目中需要计算判定,采用的是float型,如: float a < yLing, 其中:a = 2.0, y则从1.0 + 0.2*n  当n = 4时,条件成立了? ...

  4. node API buffer

    https://cnodejs.org/topic/5189ff4f63e9f8a54207f60c 1.拼接字符串时,String比buffer要快,buffer需要toString().当保存非u ...

  5. Checkpoint--相关问题

    Checkpoint是实例级别还是数据库级别? 答:数据库级别,在SQL Server关闭时,会对所有数据库逐一提交checkpoint 测试代码 USE DB0002 GO CHECKPOINT G ...

  6. 使用n g r o k将本地主机URL暴露给互联网

    在本地开发对接第三方服务的时候,对方有的时候会要求我们提供一个线上的URL地址.例如微信登录 1.下载ngrok https://ngrok.com/download 顺便注册一个账号(使用GitHu ...

  7. map函数和reduce函数、filter函数的区别

    ①从参数方面来讲:map()函数: map()包含两个参数,第一个是参数是一个函数,第二个是序列(列表或元组).其中,函数(即map的第一个参数位置的函数)可以接收一个或多个参数.reduce()函数 ...

  8. 统计进程打开了多少文件,定位too many open files

    [root@ostack1 ~]# lsof -p 18628 | wc -l 114

  9. template(定义类的模板关键字)

    template<typename T1> template<class T1> 在一般情况下二者使用方式是一样的,但有一个特例:就是当T1是一个类的时候,而这个类又有子类时候 ...

  10. Process Class (System.Diagnostics)

    import sys def hanoi(n, a, b, c): if n == 1: print('%c --> %c' % (a, c)) else: hanoi(n-1, a, c, b ...