AOP全称是Aspect Oriented Programing,通常译为面向切面编程。利用AOP可以对面向对象编程做很好的补充。

用生活中的改装车比喻,工厂用面向对象的方法制造好汽车后,车主往往有些个性化的想法,但是又不想对车进行大规模的拆卸、替换零件,这时可以买一些可替换的零件、装饰安装到汽车上,并且这些改装应该很容易拆卸,以避免验车时无法通过。

先看一个实际例子:有一个用户登录的方法,某一段时间内我们希望能够临时监控执行时间,但是又不想直接在方法上修改,用AOP方案实现如下。

UserService类

用sleep随机时间来模拟用户登录消耗的时间

  1. import java.util.Random;
  2. public class UserService {
  3. public void login(String userName, String password) {
  4. try {
  5. Thread.sleep(new Random(47).nextInt(100));
  6. } catch (InterruptedException e) {}
  7. System.out.println("UserService: 用户" + userName + "登录成功");
  8. }
  9. }

PerformanceMonitorUserService类,spring将把它当作UserService的替身(代理,Proxy)

  1. import java.util.concurrent.TimeUnit;
  2. import org.aspectj.lang.ProceedingJoinPoint;
  3. import org.aspectj.lang.annotation.Around;
  4. import org.aspectj.lang.annotation.Aspect;
  5. @Aspect
  6. public class PerformanceMonitorUserService {
  7. @Around("execution(* login(..))")
  8. public void aroundLogin(ProceedingJoinPoint pjp) {
  9. String userName = pjp.getArgs()[0].toString();
  10. long begin = System.nanoTime();
  11. try {
  12. pjp.proceed();
  13. } catch (Throwable e) {
  14. e.printStackTrace();
  15. }
  16. long end = System.nanoTime();
  17. System.out.println("PerformanceMonitorUserService: 用户" + userName + "登录耗时" + TimeUnit.MILLISECONDS.convert((end - begin), TimeUnit.NANOSECONDS) + "毫秒");
  18. }
  19. }

applicationContext.xml,放在src根目录

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  7. http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
  9. <aop:aspectj-autoproxy />
  10. <bean id="userService" class="demo.aop.UserService" />
  11. <bean class="demo.aop.PerformanceMonitorUserService" />
  12. </beans>

需要添加的jar包

测试代码

  1. import org.springframework.context.ApplicationContext;
  2. import org.springframework.context.support.ClassPathXmlApplicationContext;
  3. public class Client {
  4. public static void main(String[] args) {
  5. ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
  6. UserService userService = (UserService)ctx.getBean("userService");
  7. userService.login("Tom", "123456");
  8. }
  9. }
  1. UserService: 用户Tom登录成功
  2. PerformanceMonitorUserService: 用户Tom登录耗时71毫秒

这样就保持了UserService业务的纯粹性,避免非业务代码和业务代码混合在一起。如果希望取消时间监控,只需要删除applicationContext里的<bean class="demo.aop.PerformanceMonitorUserService" />即可。

Spring是如何做到的呢?底层的两大功臣是JDK的动态代理和CGLib动态代理技术。我们以JDK的动态代理技术来重现上面的过程

UserService接口(JDK动态代理只能为接口创建代理,所以先抽象了一个接口)

  1. public interface UserService {
  2. void login(String userName, String password);
  3. }

实现类

  1. import java.util.Random;
  2. public class UserServiceImpl implements UserService {
  3. public void login(String userName, String password) {
  4. try {
  5. Thread.sleep(new Random(47).nextInt(100));
  6. } catch (InterruptedException e) {}
  7. System.out.println("UserService: 用户" + userName + "登录成功");
  8. }
  9. }

代理类

  1. import java.lang.reflect.InvocationHandler;
  2. import java.lang.reflect.Method;
  3. import java.util.concurrent.TimeUnit;
  4. public class PerformanceMonitorUserService implements InvocationHandler {
  5. @Override
  6. public Object invoke(Object proxy, Method method, Object[] args)
  7. throws Throwable {
  8. long begin = System.currentTimeMillis();
  9. Object obj = method.invoke(target, args);
  10. long end = System.currentTimeMillis();
  11. System.out.println("PerformanceMonitorUserService: 用户" + args[0] + "登录耗时" + TimeUnit.MILLISECONDS.convert((end - begin), TimeUnit.NANOSECONDS) + "毫秒");
  12. return obj;
  13. }
  14. private Object target;
  15. public PerformanceMonitorUserService(Object target) {
  16. this.target = target;
  17. }
  18. }

测试代码

  1. import java.lang.reflect.Proxy;
  2. public class Client {
  3. public static void main(String[] args) {
  4. UserService target = new UserServiceImpl();
  5. PerformanceMonitorUserService handler = new PerformanceMonitorUserService(target);
  6. UserService proxy = (UserService)Proxy.newProxyInstance(target.getClass().getClassLoader(),
  7. target.getClass().getInterfaces(), handler);
  8. proxy.login("Tom", "123456");
  9. }
  10. }

从上面的代码可以看出,AOP的原理就是创建代理,在运行时我们开发的业务逻辑类已经被替换成添加了增强代码的代理类,而Spring帮我们省略了这些繁琐和重复的步骤。

循序渐进之Spring AOP(1) - 原理的更多相关文章

  1. 【Spring】Spring AOP实现原理

    Spring AOP实现原理 在之前的一文中介绍过Spring AOP的功能使用,但是没有深究AOP的实现原理,今天正好看到几篇好文,于是就自己整理了一下AOP实现的几种方式,同时把代理模式相关知识也 ...

  2. Spring AOP 实现原理

    什么是AOP AOP(Aspect-OrientedProgramming,面向方面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP引入 ...

  3. 何为代理?jdk动态代理与cglib代理、spring Aop代理原理浅析

    原创声明:本博客来源为本人原创作品,绝非他处摘取,转摘请联系博主 代理(proxy)的定义:为某对象提供代理服务,拥有操作代理对象的功能,在某些情况下,当客户不想或者不能直接引用另一个对象,而代理对象 ...

  4. Spring Aop底层原理详解

    Spring Aop底层原理详解(来源于csdn:https://blog.csdn.net/baomw)

  5. spring AOP底层原理实现——jdk动态代理

    spring AOP底层原理实现——jdk动态代理

  6. Spring AOP底层原理

    ------------------siwuxie095                                 Spring AOP 底层原理         AOP 即 Aspect Or ...

  7. jdk动态代理与cglib代理、spring Aop代理原理-代理使用浅析

    原创声明:本博客来源为本人原创作品,绝非他处摘取,转摘请联系博主 代理(proxy)的定义:为某对象提供代理服务,拥有操作代理对象的功能,在某些情况下,当客户不想或者不能直接引用另一个对象,而代理对象 ...

  8. Spring框架系列(9) - Spring AOP实现原理详解之AOP切面的实现

    前文,我们分析了Spring IOC的初始化过程和Bean的生命周期等,而Spring AOP也是基于IOC的Bean加载来实现的.本文主要介绍Spring AOP原理解析的切面实现过程(将切面类的所 ...

  9. Spring框架系列(10) - Spring AOP实现原理详解之AOP代理的创建

    上文我们介绍了Spring AOP原理解析的切面实现过程(将切面类的所有切面方法根据使用的注解生成对应Advice,并将Advice连同切入点匹配器和切面类等信息一并封装到Advisor).本文在此基 ...

随机推荐

  1. 手把手教你用vue-cli搭建vue项目

    手把手教你用vue-cli搭建vue项目 本篇主要是利用vue-cli来搭建vue项目,其中前提是node和npm已经安装好,文章结尾将会简单提到一个简单的例子.使用vue-cli搭建项目最开始我也是 ...

  2. 《程序员的职业素养》【PDF】下载

    <程序员的职业素养>[PDF]下载链接: https://u253469.pipipan.com/fs/253469-230382243 内容介绍 <程序员的职业素养>是编程大 ...

  3. 配置nginx支持path_info模式

    简介:我们用thinkphp,CodeIgniter框架的时候,地址基本都是IP/index.php/group_controller?***的模式,通过index.php入口访问php文件 这种模式 ...

  4. Python 3.6.3 利用 Dlib 19.7 和 opencv 实现人脸68点定位 进行人脸识别

    0.引言 介绍利用Dlib官方给的人脸识别预测器"shape_predictor_68_face_landmarks.dat"进行68点标定,利用OpenCv进行图像化处理,在人脸 ...

  5. 【python】type()、instance()

    >>> a=520 >>> type(a) <class 'int'> >>> a=' >>> type(a) &l ...

  6. Office 365实现单点登录系列(1)—域环境搭建

    Hello 小伙伴们, 2018新年快乐,作为2018年首篇文章,怎么能不给大家带来点干货呢?这篇文章其实我9月底的时候已经在MSDN上发布过了,为表诚意,我更新了这篇文章,并把它组成了一个系列,2. ...

  7. HTML知识点记录

    1.input的type设置为file时,设置multiple属性可以同时选择多个文件.

  8. ln 命令详解

    ln 命令 作用:它的功能是为某一个文件在另外一个位置建立一个同步的链接 参数:必要参数:  -b 删除,覆盖以前建立的链接  -d 允许超级用户制作目录的硬链接  -f 强制执行  -i 交互模式, ...

  9. calling c++ from golang with swig--windows dll (三)

    calling c++ from golang with swig--windows dll 三 使用动态链接库(DLL)主要有两种方式:一种通过链接导入库,在代码中直接调用DLL中的函数:另一种借助 ...

  10. Android 内存暴减的秘密?!

    作者:杨超,腾讯移动客户端开发 工程师  商业转载请联系腾讯WeTest获得授权,非商业转载请注明出处. WeTest 导读 在我这样减少了26.5M Java内存! 一文中内存优化一期已经告一段落, ...