循序渐进之Spring AOP(1) - 原理
AOP全称是Aspect Oriented Programing,通常译为面向切面编程。利用AOP可以对面向对象编程做很好的补充。
用生活中的改装车比喻,工厂用面向对象的方法制造好汽车后,车主往往有些个性化的想法,但是又不想对车进行大规模的拆卸、替换零件,这时可以买一些可替换的零件、装饰安装到汽车上,并且这些改装应该很容易拆卸,以避免验车时无法通过。
先看一个实际例子:有一个用户登录的方法,某一段时间内我们希望能够临时监控执行时间,但是又不想直接在方法上修改,用AOP方案实现如下。
UserService类
用sleep随机时间来模拟用户登录消耗的时间
- import java.util.Random;
- public class UserService {
- public void login(String userName, String password) {
- try {
- Thread.sleep(new Random(47).nextInt(100));
- } catch (InterruptedException e) {}
- System.out.println("UserService: 用户" + userName + "登录成功");
- }
- }
PerformanceMonitorUserService类,spring将把它当作UserService的替身(代理,Proxy)
- import java.util.concurrent.TimeUnit;
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.Around;
- import org.aspectj.lang.annotation.Aspect;
- @Aspect
- public class PerformanceMonitorUserService {
- @Around("execution(* login(..))")
- public void aroundLogin(ProceedingJoinPoint pjp) {
- String userName = pjp.getArgs()[0].toString();
- long begin = System.nanoTime();
- try {
- pjp.proceed();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- long end = System.nanoTime();
- System.out.println("PerformanceMonitorUserService: 用户" + userName + "登录耗时" + TimeUnit.MILLISECONDS.convert((end - begin), TimeUnit.NANOSECONDS) + "毫秒");
- }
- }
applicationContext.xml,放在src根目录
- <?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:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- 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">
- <aop:aspectj-autoproxy />
- <bean id="userService" class="demo.aop.UserService" />
- <bean class="demo.aop.PerformanceMonitorUserService" />
- </beans>
需要添加的jar包
测试代码
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class Client {
- public static void main(String[] args) {
- ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
- UserService userService = (UserService)ctx.getBean("userService");
- userService.login("Tom", "123456");
- }
- }
- UserService: 用户Tom登录成功
- PerformanceMonitorUserService: 用户Tom登录耗时71毫秒
这样就保持了UserService业务的纯粹性,避免非业务代码和业务代码混合在一起。如果希望取消时间监控,只需要删除applicationContext里的<bean class="demo.aop.PerformanceMonitorUserService" />即可。
Spring是如何做到的呢?底层的两大功臣是JDK的动态代理和CGLib动态代理技术。我们以JDK的动态代理技术来重现上面的过程
UserService接口(JDK动态代理只能为接口创建代理,所以先抽象了一个接口)
- public interface UserService {
- void login(String userName, String password);
- }
实现类
- import java.util.Random;
- public class UserServiceImpl implements UserService {
- public void login(String userName, String password) {
- try {
- Thread.sleep(new Random(47).nextInt(100));
- } catch (InterruptedException e) {}
- System.out.println("UserService: 用户" + userName + "登录成功");
- }
- }
代理类
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.util.concurrent.TimeUnit;
- public class PerformanceMonitorUserService implements InvocationHandler {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- long begin = System.currentTimeMillis();
- Object obj = method.invoke(target, args);
- long end = System.currentTimeMillis();
- System.out.println("PerformanceMonitorUserService: 用户" + args[0] + "登录耗时" + TimeUnit.MILLISECONDS.convert((end - begin), TimeUnit.NANOSECONDS) + "毫秒");
- return obj;
- }
- private Object target;
- public PerformanceMonitorUserService(Object target) {
- this.target = target;
- }
- }
测试代码
- import java.lang.reflect.Proxy;
- public class Client {
- public static void main(String[] args) {
- UserService target = new UserServiceImpl();
- PerformanceMonitorUserService handler = new PerformanceMonitorUserService(target);
- UserService proxy = (UserService)Proxy.newProxyInstance(target.getClass().getClassLoader(),
- target.getClass().getInterfaces(), handler);
- proxy.login("Tom", "123456");
- }
- }
从上面的代码可以看出,AOP的原理就是创建代理,在运行时我们开发的业务逻辑类已经被替换成添加了增强代码的代理类,而Spring帮我们省略了这些繁琐和重复的步骤。
循序渐进之Spring AOP(1) - 原理的更多相关文章
- 【Spring】Spring AOP实现原理
Spring AOP实现原理 在之前的一文中介绍过Spring AOP的功能使用,但是没有深究AOP的实现原理,今天正好看到几篇好文,于是就自己整理了一下AOP实现的几种方式,同时把代理模式相关知识也 ...
- Spring AOP 实现原理
什么是AOP AOP(Aspect-OrientedProgramming,面向方面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP引入 ...
- 何为代理?jdk动态代理与cglib代理、spring Aop代理原理浅析
原创声明:本博客来源为本人原创作品,绝非他处摘取,转摘请联系博主 代理(proxy)的定义:为某对象提供代理服务,拥有操作代理对象的功能,在某些情况下,当客户不想或者不能直接引用另一个对象,而代理对象 ...
- Spring Aop底层原理详解
Spring Aop底层原理详解(来源于csdn:https://blog.csdn.net/baomw)
- spring AOP底层原理实现——jdk动态代理
spring AOP底层原理实现——jdk动态代理
- Spring AOP底层原理
------------------siwuxie095 Spring AOP 底层原理 AOP 即 Aspect Or ...
- jdk动态代理与cglib代理、spring Aop代理原理-代理使用浅析
原创声明:本博客来源为本人原创作品,绝非他处摘取,转摘请联系博主 代理(proxy)的定义:为某对象提供代理服务,拥有操作代理对象的功能,在某些情况下,当客户不想或者不能直接引用另一个对象,而代理对象 ...
- Spring框架系列(9) - Spring AOP实现原理详解之AOP切面的实现
前文,我们分析了Spring IOC的初始化过程和Bean的生命周期等,而Spring AOP也是基于IOC的Bean加载来实现的.本文主要介绍Spring AOP原理解析的切面实现过程(将切面类的所 ...
- Spring框架系列(10) - Spring AOP实现原理详解之AOP代理的创建
上文我们介绍了Spring AOP原理解析的切面实现过程(将切面类的所有切面方法根据使用的注解生成对应Advice,并将Advice连同切入点匹配器和切面类等信息一并封装到Advisor).本文在此基 ...
随机推荐
- jsp中EL表达式不起作用的问题1
问题:在jsp页面中使用el表达式取值,取不到值,但是使用jsp中嵌套java代码可以取到值,对应代码如下: 解决: 只要在 jsp中 头文件中写上 : <%@page isELIgnored= ...
- 《编程语言实现模式》【PDF】下载
<编程语言实现模式> 编程语言实现模式旨在传授构建语言应用(工具)的经验和理念,教读者构建自己的语言应用.这里的语言应用并非特指用编译器或解释器实现编程语言,而是泛指任何处理.分析.翻译输 ...
- ES6之遍历器(Iterator)
什么是Iterator?他是一种接口,为各种不同的数据结构提供统一的访问机制,任何数据结构只要部署上Iterator接口就可以完成遍历操作(PS:个人认为他的这个遍历就是c语言里面的指针),他的作用有 ...
- ES6函数的拓展
ES里面现在支持在函数的参数直接给参数赋一个默认值,ES6支持拓展运算符(...)三个英文的点,这个形式如function(...a)这个里面...a可以接受若干的值,这个拓展运算符也可以把若干的值转 ...
- android测试
1.测试是否知道源代码: --黑盒测试 不知道代码 --白盒测试 知道源代码 2.按照测试粒度: --方法测试 --单元测试 Junit测试 --集成测试 --系统测试 3.按照测试暴力程度 --冒烟 ...
- spring boot入门 -- 介绍和第一个例子
"越来越多的企业选择使用spring boot 开发系统,spring boot牛在什么地方?难不难学?心动不如行动,让我们一起开始学习吧!" 使用Spring boot ,可以轻 ...
- Xamarin android使用Sqlite做本地存储数据库
android使用Sqlite做本地存储非常常见(打个比方就像是浏览器要做本地存储使用LocalStorage,貌似不是很恰当,大概就是这个意思). SQLite 是一个软件库,实现了自给自足的.无服 ...
- ArcGIS API for JavaScript 4.2学习笔记[12] View的弹窗(Popup)
看本文前最好对第二章(Mapping and Views)中的Map和View类有理解. 视图类有一个属性是Popup类型的popup,查阅API知道这个就是视图的弹窗,每一个View的实例都有一个p ...
- Who's in the Middle
FJ is surveying his herd to find the most average cow. He wants to know how much milk this 'median' ...
- Nodejs的运行原理-架构篇
前言 本来是想只做一个Nodejs运行原理-科普篇,但是收到了不少私信,要我多分享一些更进阶,更详细的内容,所以我会在接下来的两个月里继续更新Nodejs运行原理. PS:此系列只做Nodejs的运行 ...