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. hibernate 3.6.10 maven pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  2. 最全linux命令

    arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS / DMI ...

  3. TensorFlow文档翻译-01-TensorFlow入门

    版权声明:本文为博主原创文章,转载请指明转载地址 http://www.cnblogs.com/junyang/p/7429771.html TensorFlow入门 英文原文地址:https://w ...

  4. asp.net MVC分页

    .Net MVC  分页代码,分页的关键就是在于这几个参数pageIndex ,recordCount,pageSize ,下面是张林的网站做的一个简单的分页代码 效果如图 public class ...

  5. 干货分享!关于APP导航菜单设计你应该了解的一切

    导航菜单是人机交互的最主要的桥梁和平台,主要作用是不让用户迷失方向.现在市面上产品的菜单栏种类繁多,到底什么样的才是优秀的导航菜单设计呢?好的菜单设计不仅能提升整个产品的用户体验,而且还能让用户耳目一 ...

  6. 联想笔记本电脑 Z500除尘过程

    首先说明联想z500真的是特别难拆,主要是C面的键盘如果没有垫片的话很难拆下,建议准备好垫片再进行. 第一步 首先拆掉背面的五个螺丝钉,然后打开四个垫子注意方向,把隐藏的另外四个螺丝拆掉. 第二步 把 ...

  7. Python文件读写 - 文件r+ a+ open读写实际表现[示例]

    先说结论: 文件r+ open: 1. write()不能实现插入写,它总是覆盖写或附加写: 2. 如果文件一打开即write(),则从开头覆盖写; 3. 如果文件一打开,用f.seek()指定文件指 ...

  8. 小程序语音红包中遇到的 语音识别silk转wav格式 如何在线转 或者mp3转wav格式

    公司在开发一个小程序语音红包,现在遇到的问题就是通过微信的小程序文档接口拿到的录音文件要么是silk格式的,要么是mp3格式的 但是呢,如果要调用百度的语音接口,又必须是wav格式的.也就是说通过微信 ...

  9. Python新式类与经典类的区别

    1.新式类与经典类 在Python 2及以前的版本中,由任意内置类型派生出的类(只要一个内置类型位于类树的某个位置),都属于“新式类”,都会获得所有“新式类”的特性:反之,即不由任意内置类型派生出的类 ...

  10. gcc编译器用法

    一个用c语言写的程序把他编译成计算机可执行的文件,一般有4个步骤 /*================================================================ ...