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. 用windows自带的fsutil修改稀疏文件大小成功,但文件内容似乎丢失

    fsutil sparse setflag. fsutil sparse setrange 10M对应字节,1G对应字节.. 看文件属性,实际尺寸是小了,但内容似乎也丢了..因为自己把该文件做成虚拟盘 ...

  2. Sequelize-nodejs-4-Model usage

    Model usage模型使用 Data retrieval / Finders Finder methods are intended to query data from the database ...

  3. 鴻雁 Anser cygnoides

    鴻雁 Anser cygnoides,其中 Anser 是屬名.雁屬的模式種是 Anser anser 灰雁,在中國也有分佈,但不如鴻雁和中國人關係密切.中國人所說的「大雁」一般指鴻雁,偶爾指灰雁或是 ...

  4. PAT乙级1020

    1020 月饼 (25 分)   月饼是中国人在中秋佳节时吃的一种传统食品,不同地区有许多不同风味的月饼.现给定所有种类月饼的库存量.总售价.以及市场的最大需求量,请你计算可以获得的最大收益是多少. ...

  5. vue组件懒加载(Load On Demand)

    在Web应用程序中,系统的瓶颈常在于系统的响应速度.如果系统响应速度过慢,用户就会出现埋怨情绪,系统的价值也因此会大打折扣.因此,提高系统响应速度,是非常重要的. 懒加载(Load On Demand ...

  6. 树上差分学习笔记 + [USACO15DEC]最大流$Max \ \ Flow \ \ By$

    #\(\mathcal{\color{red}{Description}}\) \(Link\) \(FJ\)给他的牛棚的\(N(2≤N≤50,000)\)个隔间之间安装了\(N-1\)根管道,隔间编 ...

  7. C语言程序设计I—第一周教学

    这是在修改人才培养方案后第一次上C语言程序设计课程,本课程由原来的1学期80课时(周学时6)修改为2学期48(周学时4)+32(周学时2)课时的模式,开课学期也由一年二期改为大一整学年,当时修改的主要 ...

  8. 原生JavaScript技巧大收集

    原生JavaScript技巧大收集 地址:http://itindex.net/detail/47244-javascript

  9. 使用Python编写简单网络爬虫抓取视频下载资源

    我第一次接触爬虫这东西是在今年的5月份,当时写了一个博客搜索引擎.所用到的爬虫也挺智能的,起码比电影来了这个站用到的爬虫水平高多了! 回到用Python写爬虫的话题. Python一直是我主要使用的脚 ...

  10. 学习JavaSE TCP/IP协议与搭建简易聊天室

    一.TCP/IP协议 1.TCP/IP协议包括TCP.IP和UDP等 2.域名通过dns服务器转换为IP地址 3.局域网可以通过IP或者主机地址寻找到相应的主机 4.TCP是可靠的连接,效率低,且连接 ...