zoukankan      html  css  js  c++  java
  • 循序渐进之Spring AOP(1)

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

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

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

    UserService类

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

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. import java.util.Random;  
    2.   
    3. public class UserService {  
    4.     public void login(String userName, String password) {  
    5.         try {  
    6.             Thread.sleep(new Random(47).nextInt(100));  
    7.         } catch (InterruptedException e) {}  
    8.         System.out.println("UserService: 用户" + userName + "登录成功");  
    9.     }  
    10. }  

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

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

    applicationContext.xml,放在src根目录

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    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.   
    10.     <aop:aspectj-autoproxy />  
    11.     <bean id="userService" class="demo.aop.UserService" />  
    12.     <bean class="demo.aop.PerformanceMonitorUserService" />  
    13. </beans>  

    需要添加的jar包

    测试代码

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. import org.springframework.context.ApplicationContext;  
    2. import org.springframework.context.support.ClassPathXmlApplicationContext;  
    3.   
    4. public class Client {  
    5.   
    6.     public static void main(String[] args) {  
    7.         ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");  
    8.         UserService userService = (UserService)ctx.getBean("userService");  
    9.         userService.login("Tom", "123456");  
    10.     }  
    11. }  
    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. UserService: 用户Tom登录成功  
    2. PerformanceMonitorUserService: 用户Tom登录耗时71毫秒  

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

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

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

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. public interface UserService {  
    2.     void login(String userName, String password);  
    3. }  

    实现类

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. import java.util.Random;  
    2.   
    3. public class UserServiceImpl implements UserService {  
    4.   
    5.     public void login(String userName, String password) {  
    6.         try {  
    7.             Thread.sleep(new Random(47).nextInt(100));  
    8.         } catch (InterruptedException e) {}  
    9.         System.out.println("UserService: 用户" + userName + "登录成功");  
    10.     }  
    11. }  

    代理类

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. import java.lang.reflect.InvocationHandler;  
    2. import java.lang.reflect.Method;  
    3. import java.util.concurrent.TimeUnit;  
    4.   
    5. public class PerformanceMonitorUserService implements InvocationHandler {  
    6.     @Override  
    7.     public Object invoke(Object proxy, Method method, Object[] args)  
    8.             throws Throwable {  
    9.         long begin = System.currentTimeMillis();  
    10.         Object obj = method.invoke(target, args);  
    11.         long end = System.currentTimeMillis();  
    12.         System.out.println("PerformanceMonitorUserService: 用户" + args[0] + "登录耗时" + TimeUnit.MILLISECONDS.convert((end - begin), TimeUnit.NANOSECONDS) + "毫秒");  
    13.         return obj;  
    14.     }  
    15.   
    16.     private Object target;  
    17.     public PerformanceMonitorUserService(Object target) {  
    18.         this.target = target;  
    19.     }  
    20.   
    21. }  

    测试代码

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. import java.lang.reflect.Proxy;  
    2.   
    3. public class Client {  
    4.   
    5.     public static void main(String[] args) {  
    6.         UserService target = new UserServiceImpl();  
    7.         PerformanceMonitorUserService handler = new PerformanceMonitorUserService(target);  
    8.         UserService proxy = (UserService)Proxy.newProxyInstance(target.getClass().getClassLoader(),   
    9.                 target.getClass().getInterfaces(), handler);  
    10.         proxy.login("Tom", "123456");  
    11.     }  
    12. }  

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

  • 相关阅读:
    《构建之法》阅读笔记--2
    学习进度条--第九周
    团队冲刺第十天
    团队冲刺第十一天
    团队冲刺第九天
    团队冲刺第八天(4/29)
    团队冲刺第七天(4/28)
    团队冲刺第六天( 2016/4/27)
    第九章动手动脑
    第八章多态动手动脑
  • 原文地址:https://www.cnblogs.com/sa-dan/p/6837172.html
Copyright © 2011-2022 走看看