Spring Framework AOP具体解释
此前对于AOP的使用仅限于声明式事务,除此之外在实际开发中也没有遇到过与之相关的问题。近期项目中遇到了下面几点需求,细致思考之后,认为採用AOP来解决。一方面是为了以更加灵活的方式来解决这个问题,还有一方面是借此机会深入学习SpringAOP相关的内容。本文是权当本人的自己AOP学习笔记,下面需求不用AOP肯定也能解决,至于是否牵强附会,仁者见仁智者见智。
- 对部分函数的调用进行日志记录,用于观察特定问题在执行过程中的函数调用情况
- 监控部分重要函数,若抛出指定的异常,须要以短信或邮件方式通知相关人员
- 金控部分重要函数的执行时间
其实,以上需求没有AOP也能搞定,仅仅是在实现过程中比較郁闷摆了。
- 须要打印日志的函数分散在各个包中,仅仅能找到所有的函数体,手动加入日志。然而这些日志都是暂时的,待问题解决之后应该须要清除打印日志的代码,仅仅能再次手动清除^_^!
- 类似1的情况,须要捕获异常的地方太多,假设手动加入时想到非常可能明天又要手动清除,仅仅能再汗。OK,该需求相对照较固定,属于长期监控的范畴,并不需求暂时加入后再清除。然而,客户某天要求,把当中20%的异常改为短信提醒,剩下的80%改用邮件提醒。改之,两天后,客户抱怨短信太多,所有改成邮件提醒...
- 该需求通经常使用于监控某些函数的运行时间,用以推断系统运行慢的瓶颈所在。瓶颈被解决之后,烦恼同情况1
最终下定决心,採用AOP来解决!代码例如以下:
切面类TestAspect
- package com.spring.aop;
- /**
- * 切面
- *
- */
- public class TestAspect {
- public void doAfter(JoinPoint jp) {
- System.out.println("log Ending method: "
- + jp.getTarget().getClass().getName() + "."
- + jp.getSignature().getName());
- }
- public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
- long time = System.currentTimeMillis();
- Object retVal = pjp.proceed();
- time = System.currentTimeMillis() - time;
- System.out.println("process time: " + time + " ms");
- return retVal;
- }
- public void doBefore(JoinPoint jp) {
- System.out.println("log Begining method: "
- + jp.getTarget().getClass().getName() + "."
- + jp.getSignature().getName());
- }
- public void doThrowing(JoinPoint jp, Throwable ex) {
- System.out.println("method " + jp.getTarget().getClass().getName()
- + "." + jp.getSignature().getName() + " throw exception");
- System.out.println(ex.getMessage());
- }
- private void sendEx(String ex) {
- //TODO 发送短信或邮件提醒
- }
- }
- package com.spring.service;
- /**
- * 接口A
- */
- public interface AService {
- public void fooA(String _msg);
- public void barA();
- }
- package com.spring.service;
- /**
- *接口A的实现类
- */
- public class AServiceImpl implements AService {
- public void barA() {
- System.out.println("AServiceImpl.barA()");
- }
- public void fooA(String _msg) {
- System.out.println("AServiceImpl.fooA(msg:"+_msg+")");
- }
- }
- package com.spring.service;
- /**
- * Service类B
- */
- public class BServiceImpl {
- public void barB(String _msg, int _type) {
- System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")");
- if(_type == 1)
- throw new IllegalArgumentException("測试异常");
- }
- public void fooB() {
- System.out.println("BServiceImpl.fooB()");
- }
- }
ApplicationContext
- <?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"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
- default-autowire="autodetect">
- <aop:config>
- <aop:aspect id="TestAspect" ref="aspectBean">
- <!--配置com.spring.service包下全部类或接口的全部方法-->
- <aop:pointcut id="businessService"
- expression="execution(* com.spring.service.*.*(..))" />
- <aop:before pointcut-ref="businessService" method="doBefore"/>
- <aop:after pointcut-ref="businessService" method="doAfter"/>
- <aop:around pointcut-ref="businessService" method="doAround"/>
- <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/>
- </aop:aspect>
- </aop:config>
- <bean id="aspectBean" class="com.spring.aop.TestAspect" />
- <bean id="aService" class="com.spring.service.AServiceImpl"></bean>
- <bean id="bService" class="com.spring.service.BServiceImpl"></bean>
- </beans>
測试类AOPTest
- public class AOPTest extends AbstractDependencyInjectionSpringContextTests {
- private AService aService;
- private BServiceImpl bService;
- protected String[] getConfigLocations() {
- String[] configs = new String[] { "/applicationContext.xml"};
- return configs;
- }
- /**
- * 測试正常调用
- */
- public void testCall()
- {
- System.out.println("SpringTest JUnit test");
- aService.fooA("JUnit test fooA");
- aService.barA();
- bService.fooB();
- bService.barB("JUnit test barB",0);
- }
- /**
- * 測试After-Throwing
- */
- public void testThrow()
- {
- try {
- bService.barB("JUnit call barB",1);
- } catch (IllegalArgumentException e) {
- }
- }
- public void setAService(AService service) {
- aService = service;
- }
- public void setBService(BServiceImpl service) {
- bService = service;
- }
- }
执行结果例如以下:
- log Begining method: com.spring.service.AServiceImpl.fooA
- AServiceImpl.fooA(msg:JUnit test fooA)
- log Ending method: com.spring.service.AServiceImpl.fooA
- process time: 0 ms
- log Begining method: com.spring.service.AServiceImpl.barA
- AServiceImpl.barA()
- log Ending method: com.spring.service.AServiceImpl.barA
- process time: 0 ms
- log Begining method: com.spring.service.BServiceImpl.fooB
- BServiceImpl.fooB()
- log Ending method: com.spring.service.BServiceImpl.fooB
- process time: 0 ms
- log Begining method: com.spring.service.BServiceImpl.barB
- BServiceImpl.barB(msg:JUnit test barB type:0)
- log Ending method: com.spring.service.BServiceImpl.barB
- process time: 0 ms
- log Begining method: com.spring.service.BServiceImpl.barB
- BServiceImpl.barB(msg:JUnit call barB type:1)
- log Ending method: com.spring.service.BServiceImpl.barB
- method com.spring.service.BServiceImpl.barB throw exception
- 測试异常
《Spring參考手冊》中定义了下面几个AOP的重要概念,结合以上代码分析例如以下:
- 切面(Aspect):官方的抽象定义为“一个关注点的模块化,这个关注点可能会横切多个对象”,在本例中,“切面”就是类TestAspect所关注的详细行为,比如,AServiceImpl.barA()的调用就是切面TestAspect所关注的行为之中的一个。“切面”在ApplicationContext中<aop:aspect>来配置。
- 连接点(Joinpoint):程序执行过程中的某一行为,比如,AServiceImpl.barA()的调用或者BServiceImpl.barB(String _msg, int _type)抛出异常等行为。
- 通知(Advice):“切面”对于某个“连接点”所产生的动作,比如,TestAspect中对com.spring.service包下全部类的方法进行日志记录的动作就是一个Advice。当中,一个“切面”能够包括多个“Advice”,比如TestAspect
- 切入点(Pointcut):匹配连接点的断言,在AOP中通知和一个切入点表达式关联。比如,TestAspect中的全部通知所关注的连接点,都由切入点表达式execution(* com.spring.service.*.*(..))来决定
- 目标对象(Target Object):被一个或者多个切面所通知的对象。比如,AServcieImpl和BServiceImpl,当然在实际执行时,Spring AOP採用代理实现,实际AOP操作的是TargetObject的代理对象。
- AOP代理(AOP Proxy)在Spring AOP中有两种代理方式,JDK动态代理和CGLIB代理。默认情况下,TargetObject实现了接口时,则採用JDK动态代理,比如,AServiceImpl;反之,採用CGLIB代理,比如,BServiceImpl。强制使用CGLIB代理须要将
<aop:config>
的
proxy-target-class
属性设为true
通知(Advice)类型
- 前置通知(Before advice):在某连接点(JoinPoint)之前运行的通知,但这个通知不能阻止连接点前的运行。ApplicationContext中在<aop:aspect>里面使用<aop:before>元素进行声明。比如,TestAspect中的doBefore方法
- 后通知(After advice):当某连接点退出的时候运行的通知(不论是正常返回还是异常退出)。ApplicationContext中在<aop:aspect>里面使用<aop:after>元素进行声明。比如,TestAspect中的doAfter方法,所以AOPTest中调用BServiceImpl.barB抛出异常时,doAfter方法仍然运行
- 返回后通知(After return advice):在某连接点正常完毕后运行的通知,不包含抛出异常的情况。ApplicationContext中在<aop:aspect>里面使用<after-returning>元素进行声明。
- 围绕通知(Around advice):包围一个连接点的通知,类似Web中Servlet规范中的Filter的doFilter方法。能够在方法的调用前后完毕自己定义的行为,也能够选择不运行。ApplicationContext中在<aop:aspect>里面使用<aop:around>元素进行声明。比如,TestAspect中的doAround方法。
- 抛出异常后通知(After throwing advice): 在方法抛出异常退出时运行的通知。 ApplicationContext中在<aop:aspect>里面使用<aop:after-throwing>元素进行声明。比如,TestAspect中的doThrowing方法。
切入点表达式
- 通常情况下,表达式中使用”execution“就能够满足大部分的要求。表达式格式例如以下:
- execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
modifiers-pattern:方法的操作权限
ret-type-pattern:返回值
declaring-type-pattern:方法所在的包
name-pattern:方法名
parm-pattern:參数名
throws-pattern:异常
当中,除ret-type-pattern和name-pattern之外,其它都是可选的。上例中,execution(* com.spring.service.*.*(..))表示com.spring.service包下,返回值为随意类型;方法名随意;參数不作限制的全部方法。
- 通知參数
能够通过args来绑定參数,这样就能够在通知(Advice)中訪问详细參数了。比如,<aop:aspect>配置例如以下
- <aop:config>
- <aop:aspect id="TestAspect" ref="aspectBean">
- <aop:pointcut id="businessService"
- expression="execution(* com.spring.service.*.*(String,..)) and args(msg,..)" />
- <aop:after pointcut-ref="businessService" method="doAfter"/>
- </aop:aspect>
- </aop:config>
TestAspect的doAfter方法中就能够訪问msg參数,但这样以来AService中的barA()和BServiceImpl中的barB()就不再是连接点,由于execution(* com.spring.service.*.*(String,..))仅仅配置第一个參数为String类型的方法。当中,doAfter方法定义例如以下:
- public void doAfter(JoinPoint jp,String msg)
- 訪问当前的连接点
不论什么通知(Advice)方法能够将第一个參数定义为
类型。
org.aspectj.lang.JoinPointJoinPoint
接口提供了一系列实用的方法, 比方getArgs()
(返回方法參数)、getThis()
(返回代理对象)、getTarget()
(返回目标)、getSignature()
(返回正在被通知的方法相关信息)和toString()
(打印出正在被通知的方法的实用信息。
Spring Framework AOP具体解释的更多相关文章
- 转-Spring Framework中的AOP之around通知
Spring Framework中的AOP之around通知 http://blog.csdn.net/xiaoliang_xie/article/details/7049183 标签: spring ...
- Chapter 4: Spring and AOP:Spring's AOP Framework -- draft
Spring's AOP Framework Let's begin by looking at Spring's own AOP framework - a proxy-based framewor ...
- Spring Framework 之AOP
Spring Framework 之AOP 目录 Spring Framework 之AOP 问题 AOP概述 AOP知识 1.连接点(Joinpoint) 2.切点(PointCut) 3.增强(A ...
- 框架应用:Spring framework (二) - AOP技术
基础概念 线程中的方法栈 java程序虚拟机启动时会载入程序码,虚拟机会为每一条正在运行的线程生成一个方法调用栈,线程以方法运行为执行单位. AOP概念以及目标 AOP是面向切面编程,其实就是在不修改 ...
- 【Spring Framework】Spring入门教程(六)Spring AOP使用
Spring的AOP 动态代理模式的缺陷是: 实现类必须要实现接口 -JDK动态代理 无法通过规则制定拦截无需功能增强的方法. Spring-AOP主要弥补了第二个不足,通过规则设置来拦截方法,并对方 ...
- 【Spring Framework】Spring入门教程(五)AOP思想和动态代理
本文主要讲解内容如下: Spring的核心之一 - AOP思想 (1) 代理模式- 动态代理 ① JDK的动态代理 (Java官方) ② CGLIB 第三方代理 AOP概述 什么是AOP(面向切面编程 ...
- Spring Framework 5.0.0.M3中文文档 翻译记录 Part I. Spring框架概览1-2.2
Part I. Spring框架概览 The Spring Framework is a lightweight solution and a potential one-stop-shop for ...
- Spring系列(零) Spring Framework 文档中文翻译
Spring 框架文档(核心篇1和2) Version 5.1.3.RELEASE 最新的, 更新的笔记, 支持的版本和其他主题,独立的发布版本等, 是在Github Wiki 项目维护的. 总览 历 ...
- Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion(一)
题外话:本篇是对之前那篇的重排版.并拆分成两篇,免得没了看的兴趣. 前言 在Spring Framework官方文档中,这三者是放到一起讲的,但没有解释为什么放到一起.大概是默认了读者都是有相关经验的 ...
随机推荐
- Vistual Studio 2012更换皮肤
早就装上VS2012了,可是除了在家里练习玩玩的时候使用外,在公司都还在用2010,也没好好研究过2012.这两天把公司的电脑换了系统,也就把vs换成了2012.可是看着不是白白的皮肤就是深色的皮肤, ...
- Ember.js - About
Ember.js - About More Productive Out of the Box. Write dramatically less code with Ember's Handleb ...
- Cocos2d-x3.0模版容器具体解释之二:cocos2d::Map<K,V>
1.概述: 版本号: v3.0 beta 语言: C++ 定义在 "COCOS2DX_ROOT/cocos/base" 路径下的 "CCMap.h" 的头文件里 ...
- BLE简介和Android BLE编程
一.BLE和BT区别 其实我知道许多程序员不太喜欢阅读除了代码以外的文档,因为有时这些过于冗长的文档对编程并没有更多的好处,有了协议,接口,demo差不多很多人就能写出很好质量的代码了.但其实更深入的 ...
- EasyUI - ValidateBox 验证组件
基本效果: 效果: Html代码: <input id="email" /> JS代码: 默认的有四种验证方式: email:验证邮箱 url:验证url length ...
- IT段子,娱乐一下
1.我是个程序员,一天我坐在路边一边喝水一边苦苦检查bug.这时一个乞丐在我边上坐下了,开始要饭,我觉得可怜,就给了他1块钱,然后接着调试程序.他可能生意不好,就无聊的看看我在干什么,然后过了一会,他 ...
- Oracle 创建索引的基本规则总结
1. 选择索引字段的原则: 在WHERE子句中最频繁使用的字段 联接语句中的联接字段 选择高选择性的字段(如果很少的字段拥有相同值,即有很多独特值,则选择性很好) Oracle在UNIQUE和主键字 ...
- 水平线、垂直线——axure线框图部件库介绍
1. 将水平线.垂直线拖动到axure页面编辑区域,如图: 2. 水平线.垂直线相关属性设置 主要属性有.线条的颜色.粗细.线条的样式.箭头的样式 来自:非原型不设计
- Spring Mobile是如何判断访问设备的类型的
Spring最近换域名了,去转转,发现了一个有意思的项目:spring mobile. http://projects.spring.io/spring-mobile/ 这个项目有很多实用的功能,如识 ...
- uvc摄像头代码解析7
13.uvc视频初始化 13.1 uvc数据流控制 struct uvc_streaming_control { __u16 bmHint; __u8 bFormatIndex; //视频格式索引 _ ...