Spring AOP(面向方面编程)框架,用于在模块化方面的横切关注点。简单得说,它只是一个拦截器拦截一些过程,例如,当一个方法执行,Spring AOP 可以劫持一个执行的方法,在方法执行之前或之后添加额外的功能。
在Spring AOP中,有 4 种类型通知(advices)的支持:
  • 通知(Advice)之前 - 该方法执行前运行.                                               (实现 MethodBeforeAdvice接口)
  • 通知(Advice)返回之后 – 运行后,该方法返回一个结果                       (实现AfterReturningAdvice接口)
  • 通知(Advice)抛出之后 – 运行方法抛出异常后,                                  (实现ThrowsAdvice接口,并创建一个afterThrowing方法拦截)
  • 环绕通知 – 环绕方法执行运行,结合以上这三个通知。                      (实现MethodInterceptor接口;必须调用“methodInvocation.proceed();)
下面的例子显示Spring AOP 通知如何工作。
简单的 Spring 例子
创建一个简单的客户服务类及一个print方法作为演示。
package com.yiibai.customer.services;

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();
} }

File : applicationContext.xml – 一个bean配置文件

<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.yiibai.customer.services.CustomerService">
<property name="name" value="YiiBaii Mook Kim" />
<property name="url" value="http://www.yiibai.com" />
</bean> </beans>

执行它

package com.yiibai.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.yiibai.customer.services.CustomerService; public class App {
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext(
new String[] { "Spring-Customer.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 : Yiibai Mook Kim
*************************
Customer website : http://www.yiibai.com
*************************
一个简单的Spring项目用来注入(DI)bean和输出一些字符串。

Spring AOP 通知

现在,附加 Spring AOP 建议到上述的客户服务。

1. 之前通知

它会在方法执行之前执行。创建一个实现 MethodBeforeAdvice 接口的类。
package com.yiibai.aop;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice; public class HijackBeforeMethod implements MethodBeforeAdvice
{
@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("HijackBeforeMethod : Before method hijacked!");
}
}
在 bean 配置文件(applicationContext.xml),创建一个 bean 的 HijackBeforeMethod 类,并命名为“customerServiceProxy” 作为一个新的代理对象。
  • ‘target’ – 定义你想拦截的bean。
  • ‘interceptorNames’ – 定义要应用这个代理/目标对象的类(通知)。
<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.yiibai.customer.services.CustomerService">
<property name="name" value="Yiibai Mook Kim" />
<property name="url" value="http://www.yiibai.com" />
</bean> <bean id="hijackBeforeMethodBean" class="com.yiibai.aop.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>
再次运行它,现在得到新的 customerServiceProxy bean,而不是原来的CustomerService bean。
package com.yiibai.common;

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

输出结果

*************************
HijackBeforeMethod : Before method hijacked!
Customer name : Yiibai Mook Kim
*************************
HijackBeforeMethod : Before method hijacked!
Customer website : http://www.yiibai.com
*************************
HijackBeforeMethod : Before method hijacked!
它将运行 HijackBeforeMethod 的 before() 方法,在每个 CustomerService 的方法之前执行。
2.返回后通知
该方法返回一个结果之后它将执行。创建一个实现AfterReturningAdvice接口的类。
package com.yiibai.aop;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice; public class HijackAfterMethod implements AfterReturningAdvice
{
@Override
public void afterReturning(Object returnValue, Method method,
Object[] args, Object target) throws Throwable {
System.out.println("HijackAfterMethod : After method hijacked!");
}
}
bean配置文件
<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.yiibai.customer.services.CustomerService">
<property name="name" value="Yong Mook Kim" />
<property name="url" value="http://www.yiibai.com" />
</bean> <bean id="hijackAfterMethodBean" class="com.yiibai.aop.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>
再次运行,输出
*************************
Customer name : Yiibai Mook Kim
HijackAfterMethod : After method hijacked!
*************************
Customer website : http://www.yiibai.com
HijackAfterMethod : After method hijacked!
*************************
它将运行 HijackAfterMethod 的 afterReturning()方法,在每次 CustomerService 方法返回结果之后。
3.抛出后通知
它将在执行方法抛出一个异常后。创建一个实现ThrowsAdvice接口的类,并创建一个afterThrowing方法拦截抛出:IllegalArgumentException异常。
package com.yiibai.aop;

import org.springframework.aop.ThrowsAdvice;

public class HijackThrowException implements ThrowsAdvice {
public void afterThrowing(IllegalArgumentException e) throws Throwable {//afterThrowing:不能修改;IllegalArgumentException:捕获什么异常就发什么异常类型(Throwable:捕获任何异常);
System.out.println("HijackThrowException : Throw exception hijacked!");
}
}
bean配置文件
<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.yiibai.customer.services.CustomerService">
<property name="name" value="Yong Mook Kim" />
<property name="url" value="http://www.yiibai.com" />
</bean> <bean id="hijackThrowExceptionBean" class="com.yiibai.aop.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>

再次运行,输出
*************************
Customer name : Yiibai Mook Kim
*************************
Customer website : http://www.yiibai.com
*************************
HijackThrowException : Throw exception hijacked!
它将运行 HijackThrowException 的 afterThrowing()方法,如果 CustomerService 的方法抛出异常。
4.环绕通知

它结合了上面的三个通知,在方法执行过程中执行。创建一个实现了MethodInterceptor接口的类。必须调用“methodInvocation.proceed();” 继续在原来的方法执行,否则原来的方法将不会执行。

package com.yiibai.aop;

import java.util.Arrays;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation; public class HijackAroundMethod implements MethodInterceptor { //MethodInterceptor :方法拦截器
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable { System.out.println("Method name : "
+ methodInvocation.getMethod().getName());
System.out.println("Method arguments : "
+ Arrays.toString(methodInvocation.getArguments())); // same with MethodBeforeAdvice
System.out.println("HijackAroundMethod : Before method hijacked!"); try {
// proceed to original method call
Object result = methodInvocation.proceed(); // same with AfterReturningAdvice
System.out.println("HijackAroundMethod : Before after hijacked!"); return result; } catch (IllegalArgumentException e) {
// same with ThrowsAdvice
System.out.println("HijackAroundMethod : Throw exception hijacked!");
throw e;
}
}
}
bean配置文件
<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.yiibai.customer.services.CustomerService">
<property name="name" value="Yong Mook Kim" />
<property name="url" value="http://www.yiibai.com" />
</bean> <bean id="hijackAroundMethodBean" class="com.yiibai.aop.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>
再次运行,输出

*************************
Method name : printName
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer name : YiiBai Mook Kim
HijackAroundMethod : Before after hijacked!
*************************
Method name : printURL
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer website : http://www.yiibai.com
HijackAroundMethod : Before after hijacked!
*************************
Method name : printThrowException
Method arguments : []
HijackAroundMethod : Before method hijacked!
HijackAroundMethod : Throw exception hijacked!

它将运行HijackAroundMethod 的 invoke()方法,在每一个 CustomerService 方法执行后。

Spring学习(十五)----- Spring AOP通知实例 – Advice的更多相关文章

  1. Spring学习十五----------Spring AOP API的Pointcut、advice及 ProxyFactoryBean相关内容

    © 版权声明:本文为博主原创文章,转载请注明出处 实例: 1.项目结构 2.pom.xml <project xmlns="http://maven.apache.org/POM/4. ...

  2. spring学习 十四 注解AOP 通知传递参数

    我们在对切点进行增强时,不建议对切点进行任何修改,因此不加以使用@PointCut注解打在切点上,尽量只在Advice上打注解(Before,After等),如果要在通知中接受切点的参数,可以使用Jo ...

  3. spring学习 十五 spring的自动注入

    一  :在 Spring 配置文件中对象名和 ref=”id” ,id 名相同使用自动注入,可以不配置<property/>,对应的注解@Autowired的作用 二: 两种配置办法 (1 ...

  4. Spring学习十四----------Spring AOP实例

    © 版权声明:本文为博主原创文章,转载请注明出处 实例 1.项目结构 2.pom.xml <project xmlns="http://maven.apache.org/POM/4.0 ...

  5. Spring学习(十六)----- Spring AOP实例(Pointcut(切点),Advisor)

    在上一个Spring AOP通知的例子,一个类的整个方法被自动拦截.但在大多数情况下,可能只需要一种方式来拦截一个或两个方法,这就是为什么引入'切入点'的原因.它允许你通过它的方法名来拦截方法.另外, ...

  6. Spring AOP通知实例 – Advice

    Spring AOP(面向方面编程)框架,用于在模块化方面的横切关注点.简单得说,它只是一个拦截器拦截一些过程,例如,当一个方法执行,Spring AOP 可以劫持一个执行的方法,在方法执行之前或之后 ...

  7. spring boot(十五)spring boot+thymeleaf+jpa增删改查示例

    快速上手 配置文件 pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 <dependency> <groupId>org.springframework.b ...

  8. Spring 学习十五 AOP

    http://www.hongyanliren.com/2014m12/22797.html 1: 通知(advice): 就是你想要的功能,也就是安全.事物.日子等.先定义好,在想用的地方用一下.包 ...

  9. Spring学习(十八)----- Spring AOP+AspectJ注解实例

    我们将向你展示如何将AspectJ注解集成到Spring AOP框架.在这个Spring AOP+ AspectJ 示例中,让您轻松实现拦截方法. 常见AspectJ的注解: @Before – 方法 ...

随机推荐

  1. Skype for Business Server 2015 企业语音部署和配置

    Skype for Business Server 2015包含的企业语音功能可实现更丰富的通信和协作.例如,可以将企业语音部署配置为启用Skype for Business Server 2015客 ...

  2. Hadoop HBase概念学习系列之优秀行键设计(十六)

    我们通过行键访问HBase.尽管使用扫描过滤器可以一次性指明大量的键,但是HBase仅仅能够根据行键识别出一行. 优秀的行键设计可以保证良好的HBase性能. 1.行键存在于HBase中的每一个单元格 ...

  3. Log4net 使用之 自定义字段

    Log4net 是.Net下一个非常优秀的开源日志记录组件.Log4net记录日志的功能非常强大.它可以将日志分不同的等级,以不同的格式,输出到不同的媒介. 由于业务需要,计划为日志增加2个字段,除了 ...

  4. 利用skipList(跳表)来实现排序(待补充)

    用于排名的数据结构 一般排序为利用堆排序(二叉树)和利用skipList(跳表)的方式 redis中SortedSet利用skipList(跳表)来实现排序,复杂度为O(logn),利用空间换时间,类 ...

  5. Hibernate入门步骤及概念

    1.什么是Hibernate Hibernate是一个开发源代码的对象关系映射框架,它对JDBC进行非常轻量级的对象封装,使得程序员可以随心所欲地使用对象编程思维来操纵数据库.Hibernate可以应 ...

  6. 基于easyui开发Web版Activiti流程定制器详解(二)——文件列表

    上一篇我们介绍了目录结构,这篇给大家整理一个文件列表以及详细说明,方便大家查找文件. 由于设计器文件主要保存在wf/designer和js/designer目录下,所以主要针对这两个目录进行详细说明. ...

  7. 理解JVM——JVM的结构

    这是理解JVM的第一篇文章,这篇文章主要介绍JVM的总体结构和每一个部分的功能.内容比较少,对于每一个部分详细的内容,放到后面的文章中,逐步展开.这个系列总结完,应该会对JVM有一个整体且深入的认识了 ...

  8. BZOJ3530:[SDOI2014]数数(AC自动机,数位DP)

    Description 我们称一个正整数N是幸运数,当且仅当它的十进制表示中不包含数字串集合S中任意一个元素作为其子串.例如当S=(22,333,0233)时,233是幸运数,2333.20233.3 ...

  9. Day16 IO流

    流的概念和作用 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象.即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作. Ja ...

  10. Linux终端里的记录器

    我们在调试程序的时候,免不了要去抓一些 log ,然后进行分析. 如果 log 量不是很大的话,那很简单,只需简单的复制粘贴就好. 但是如果做一些压力测试,产生大量 log ,而且系统内存又比较小(比 ...