Spring3系列9- Spring AOP——Advice

  Spring AOP即Aspect-oriented programming,面向切面编程,是作为面向对象编程的一种补充,专门用于处理系统中分布于各个模块(不同方法)中的交叉关注点的问题。简单地说,就是一个拦截器(interceptor)拦截一些处理过程。例如,当一个method被执行,Spring AOP能够劫持正在运行的method,在method执行前或者后加入一些额外的功能。

在Spring AOP中,支持4中类型的通知(Advice)

Before advice      ——method执行前通知

After returning advice ——method返回一个结果后通知

After throwing advice – method抛出异常后通知

Around advice – 环绕通知,结合了以上三种

下边这个例子解释Spring AOP怎样工作。

首先一个简单的不使用AOP的例子。

先创建一个简单的Service,为了稍后演示,这个类中加了几个简单的打印method。

CustomerService.java如下:

package com.lei.demo.aop.advice;

public class CustomerService {

    private String name;
private String url; public void setName(String name) {
this.name = name;
} public void setUrl(String url) {
this.url = url;
} public void printName() {
System.out.println("Customer name : " + this.name);
} public void printURL() {
System.out.println("Customer website : " + this.url);
} public void printThrowException() {
throw new IllegalArgumentException();
} }

Xml配置文件Apring-AOP-Advice.xml如下:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerService" class="com.lei.demo.aop.advice.CustomerService">
<property name="name" value="LeiOOLei" />
<property name="url" value="http://www.cnblogs.com/leiOOlei/" />
</bean> </beans>

运行以下代码App.java:

package com.lei.demo.aop.advice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext(
new String[] { "Spring-AOP-Advice.xml" }); CustomerService cust = (CustomerService) appContext.getBean("customerService"); System.out.println("*************************");
cust.printName();
System.out.println("*************************");
cust.printURL();
System.out.println("*************************");
try {
cust.printThrowException();
} catch (Exception e) { } } }

运行结果:

*************************

Customer name : LeiOOLei

*************************

Customer website : http://www.cnblogs.com/leiOOlei/

*************************

1.      Before Advice

创建一个实现了接口MethodBeforeAdvice的class,method运行前,将运行下边的代码

HijackBeforeMethod.java如下:

package com.lei.demo.aop.advice;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice; public class HijackBeforeMethod implements MethodBeforeAdvice { public void before(Method arg0, Object[] args, Object target)
throws Throwable {
System.out.println("HijackBeforeMethod : Before method hijacked!"); } }

在配置文件中加入新的bean配置HijackBeforeMethod,然后创建一个新的代理(proxy),命名为customerServiceProxy。

“target”定义你想劫持哪个bean;

“interceptorNames”定义你想用哪个class(advice)劫持target。

Apring-AOP-Advice.xml如下:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerService" class="com.lei.demo.aop.advice.CustomerService">
<property name="name" value="LeiOOLei" />
<property name="url" value="http://www.cnblogs.com/leiOOlei/" />
</bean> <bean id="hijackBeforeMethodBean" class="com.lei.demo.aop.advice.HijackBeforeMethod" /> <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="customerService" />
<property name="interceptorNames">
<list>
<value>hijackBeforeMethodBean</value>
</list>
</property>
</bean> </beans>

注意:

用Spring proxy之前,必须添加CGLIB2类库,,以下是pom.xml依赖

  <dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>

运行如下代码,注意代理

App.java如下

package com.lei.demo.aop.advice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext(
new String[] { "Spring-AOP-Advice.xml" }); CustomerService cust = (CustomerService) appContext.getBean("customerServiceProxy"); System.out.println("使用Spring AOP 如下");
System.out.println("*************************");
cust.printName();
System.out.println("*************************");
cust.printURL();
System.out.println("*************************"); try {
cust.printThrowException();
} catch (Exception e) { } } }

输出结果:

使用Spring AOP 如下

*************************

HijackBeforeMethod : Before method hijacked!

Customer name : LeiOOLei

*************************

HijackBeforeMethod : Before method hijacked!

Customer website : http://www.cnblogs.com/leiOOlei/

*************************

HijackBeforeMethod : Before method hijacked!

每一个customerService的method运行前,都将先执行HijackBeforeMethod的before方法。

2.      After Returning Advice

创建一个实现了接口AfterReturningAdvice的class,method运行后,直到返回结果后,才运行下边的代码,如果没有返回结果,将不运行切入的代码。

HijackAfterMethod.java如下:

package com.lei.demo.aop.advice;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice; public class HijackAfterMethod implements AfterReturningAdvice { public void afterReturning(Object returnValue, Method method, Object[] args,
Object target) throws Throwable {
System.out.println("HijackAfterMethod : After method hijacked!"); } }

修改bean配置文件,加入hijackAfterMethodBean配置,Apring-AOP-Advice.xml如下:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerService" class="com.lei.demo.aop.advice.CustomerService">
<property name="name" value="LeiOOLei" />
<property name="url" value="http://www.cnblogs.com/leiOOlei/" />
</bean> <bean id="hijackBeforeMethodBean" class="com.lei.demo.aop.advice.HijackBeforeMethod" />
<bean id="hijackAfterMethodBean" class="com.lei.demo.aop.advice.HijackAfterMethod" /> <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="customerService" />
<property name="interceptorNames">
<list>
<value>hijackAfterMethodBean</value>
</list>
</property>
</bean> </beans>

现在再运行App.java后输出如下:

使用Spring AOP 如下

*************************

Customer name : LeiOOLei

HijackAfterMethod : After method hijacked!

*************************

Customer website : http://www.cnblogs.com/leiOOlei/

HijackAfterMethod : After method hijacked!

*************************

可以看到输出结果,每一个customerService的method运行返回结果后,都将再执行HijackAfterMethod的afterReturning方法。但是执行到cust.printThrowException()后,直接抛出异常,方法没有正常执行完毕(或者说没有返回结果),所以不运行切入的afterReturning方法。

3.      Afetr Throwing Advice

创建一个实现了ThrowsAdvice接口的class,劫持IllegalArgumentException异常,目标method运行时,抛出IllegalArgumentException异常后,运行切入的方法。

HijackThrowException.java如下:

package com.lei.demo.aop.advice;

import org.springframework.aop.ThrowsAdvice;

import sun.awt.SunToolkit.IllegalThreadException;

public class HijackThrowException implements ThrowsAdvice {

    public void afterThrowing(IllegalArgumentException e) throws Throwable {
System.out.println("HijackThrowException : Throw exception hijacked!");
} }

修改bean配置文件,加入了hijackThrowExceptionBean,Apring-AOP-Advice.xml如下:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerService" class="com.lei.demo.aop.advice.CustomerService">
<property name="name" value="LeiOOLei" />
<property name="url" value="http://www.cnblogs.com/leiOOlei/" />
</bean> <bean id="hijackBeforeMethodBean" class="com.lei.demo.aop.advice.HijackBeforeMethod" />
<bean id="hijackAfterMethodBean" class="com.lei.demo.aop.advice.HijackAfterMethod" />
<bean id="hijackThrowExceptionBean" class="com.lei.demo.aop.advice.HijackThrowException" /> <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="customerService" />
<property name="interceptorNames">
<list>
<value>hijackThrowExceptionBean</value>
</list>
</property>
</bean> </beans>

运行结果如下:

使用Spring AOP 如下

*************************

Customer name : LeiOOLei

*************************

Customer website : http://www.cnblogs.com/leiOOlei/

*************************

HijackThrowException : Throw exception hijacked!

当运行CustomerService中的printThrowException方法时,认为的抛出IllegalArgumentException异常,被HijackThrowException截获,运行其中的afterThrowing方法。注意,如果抛出异常不是IllegalArgumentException,则不能被截获。

4.      Around Advice

结合了以上3种形式的Advice,创建一个实现了接口MethodInterceptor的class,你必须通过methodInvocation.proceed()来调用原来的方法,即通过调用methodInvocation.proceed()来调用CustomerService中的每一个方法,当然也可以不调用原方法。

HijackAroundMethod.java如下:

package com.lei.demo.aop.advice;

import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation; public class HijackAroundMethod implements MethodInterceptor { public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("Method name : "
+ methodInvocation.getMethod().getName());
System.out.println("Method arguments : "
+ Arrays.toString(methodInvocation.getArguments())); // 相当于 MethodBeforeAdvice
System.out.println("HijackAroundMethod : Before method hijacked!"); try {
// 调用原方法,即调用CustomerService中的方法
Object result = methodInvocation.proceed(); // 相当于 AfterReturningAdvice
System.out.println("HijackAroundMethod : After method hijacked!"); return result; } catch (IllegalArgumentException e) {
// 相当于 ThrowsAdvice
System.out.println("HijackAroundMethod : Throw exception hijacked!");
throw e;
}
} }

修改bean配置文件,加入了hijackAroundMethodBean,Apring-AOP-Advice.xml如下:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerService" class="com.lei.demo.aop.advice.CustomerService">
<property name="name" value="LeiOOLei" />
<property name="url" value="http://www.cnblogs.com/leiOOlei/" />
</bean> <bean id="hijackBeforeMethodBean" class="com.lei.demo.aop.advice.HijackBeforeMethod" />
<bean id="hijackAfterMethodBean" class="com.lei.demo.aop.advice.HijackAfterMethod" />
<bean id="hijackThrowExceptionBean" class="com.lei.demo.aop.advice.HijackThrowException" />
<bean id="hijackAroundMethodBean" class="com.lei.demo.aop.advice.HijackAroundMethod" /> <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="customerService" />
<property name="interceptorNames">
<list>
<value>hijackAroundMethodBean</value>
</list>
</property>
</bean> </beans>

执行App.java,输出结果:

使用Spring AOP 如下

*************************

Method name : printName

Method arguments : []

HijackAroundMethod : Before method hijacked!

Customer name : LeiOOLei

HijackAroundMethod : After method hijacked!

*************************

Method name : printURL

Method arguments : []

HijackAroundMethod : Before method hijacked!

Customer website : http://www.cnblogs.com/leiOOlei/

HijackAroundMethod : After method hijacked!

*************************

Method name : printThrowException

Method arguments : []

HijackAroundMethod : Before method hijacked!

HijackAroundMethod : Throw exception hijacked!

CustomerService中每一个方法的调用,都会执行HijackAroundMethod中的invoke方法,可以看到整个切入点将目标around。

大多数的Spring开发者只用Around Advice,因为它能够实现所有类型的Advice。在实际的项目开发中,我们还是要尽量选择适合的Advice。

在以上的例子中,CustomerService中的所有方法都被自动拦截,但是大多数情况下,我们不需要拦截一个class中的所有方法,而是拦截符合条件的方法。这时,我们就需要用到Pointcut and Advice,即切入点和通知,以后的章节中会逐渐介绍。

Spring3系列9- Spring AOP——Advice的更多相关文章

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

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

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

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

  3. Spring框架系列(11) - Spring AOP实现原理详解之Cglib代理实现

    我们在前文中已经介绍了SpringAOP的切面实现和创建动态代理的过程,那么动态代理是如何工作的呢?本文主要介绍Cglib动态代理的案例和SpringAOP实现的原理.@pdai Spring框架系列 ...

  4. Spring框架系列(12) - Spring AOP实现原理详解之JDK代理实现

    上文我们学习了SpringAOP Cglib动态代理的实现,本文主要是SpringAOP JDK动态代理的案例和实现部分.@pdai Spring框架系列(12) - Spring AOP实现原理详解 ...

  5. spring AOP advice 类型 和 通用的切点的配置方式

    spring aop advice的类型: 1.前置通知(before advice) 2.返回后通知(after returning advice) 3.抛出异常后通知(after throwing ...

  6. Spring3系列6 - Spring 表达式语言(Spring EL)

    Spring3系列6-Spring 表达式语言(Spring EL) 本篇讲述了Spring Expression Language —— 即Spring3中功能丰富强大的表达式语言,简称SpEL.S ...

  7. 【Spring系列】Spring AOP面向切面编程

    前言 接上一篇文章,在上午中使用了切面做防重复控制,本文着重介绍切面AOP. 在开发中,有一些功能行为是通用的,比如.日志管理.安全和事务,它们有一个共同点就是分布于应用中的多处,这种功能被称为横切关 ...

  8. Spring5.0源码学习系列之Spring AOP简述

    前言介绍 附录:Spring源码学习专栏 在前面章节的学习中,我们对Spring框架的IOC实现源码有了一定的了解,接着本文继续学习Springframework一个核心的技术点AOP技术. 在学习S ...

  9. SSH框架系列:Spring AOP应用记录日志Demo

    分类: [java]2013-12-10 18:53 724人阅读 评论(0) 收藏 举报 1.简介 Spring 中的AOP为Aspect Oriented Programming的缩写,面向切面编 ...

  10. spring aop advice

    1.前置通知(BeforeAdvice): import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAd ...

随机推荐

  1. 从“程序员转行卖烧饼”想到IT人创业

    我的一个朋友最近总在跟我念叨着“我不想做开发了,整天累死累活写程序,也攒不下几个钱.我想辞职搞点啥!” 我问他:“你想搞点啥?”. 他说:“搞啥都比做开发强,做个网站赚广告费,接私活……实在不行我去卖 ...

  2. [WinAPI] 串口读写

    #include <stdio.h> #include <stdlib.h> #include <windows.h> HANDLE hComm; OVERLAPP ...

  3. [RabbitMQ] AMQP close-reason, initiated by Library, code=541

    RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachabl ...

  4. 错误The request sent by the client was syntactically incorrect ()的解决

    http://www.cnblogs.com/xiandedanteng/p/4168609.html 这个错误是SpringMVC报出来的,见到它意味着html/jsp页面的控件名称 和 contr ...

  5. redis 内存

    ziplist:http://blog.csdn.net/benbendy1984/article/details/7796956 redis 内部存储结构:http://www.searchtb.c ...

  6. paip 自定义输入法多多输入法词库的备份导出以及导入

    paip 自定义输入法词库的备份导出以及导入 作者Attilax 艾龙,  EMAIL:1466519819@qq.com 来源:attilax的专栏 地址:http://blog.csdn.net/ ...

  7. JAVA学习Swing章节JPanel和JScrollPane面板的简单学习

    package com.swing; import java.awt.Container; import java.awt.GridLayout; import javax.swing.JButton ...

  8. Leetcode 102 Binary Tree Level Order Traversal 二叉树+BFS

    二叉树的层次遍历 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * ...

  9. Android shape 渐变!描边!圆角!示例详解

    看看shape的用法,确实很有帮助.这里我偷懒转一篇比较详细的帖子,和大家一起进步~! Android 中常常使用shape来定义控件的一些显示属性,今天看了一些shape的使用,对shape有了大体 ...

  10. MyEclipse8.6中提交SVN报错

    上周五(11月27日)的时候,从TortoiseSVN提交项目报错,然后直接从MyEclipse中检出来,修改后提交同样报错. MyEclipse8.6中提交SVN报错,错误提示如下: commit ...