---
title: "Spring学习笔记(三)——继续AOP"
author: "llc"
date: "2009-11-13T10:22:30Z"
tags: []
slug: "spring-aop"
draft: false
lastmod: "2009-11-13T10:22:30Z"
id: 515985
url: "https://llc.iteye.com/blog/515985"
---

上次我们谈到了简单的AOP，今天我们继续旅程。

    上次我们谈到了对一个对象的方法进行切割，那如果要对两个、3个对象呢？我们发现：

&lt;bean id="result" class="org.springframework.aop.framework.ProxyFactoryBean"&gt;  
  &lt;property name="interceptorNames"&gt;  
   &lt;list&gt;  
    &lt;value&gt;interceptor&lt;/value&gt;  
   &lt;/list&gt;  
  &lt;/property&gt;  
  &lt;property name="target" ref="wash"&gt;&lt;/property&gt;  
  &lt;property name="proxyTargetClass" value="true"&gt;&lt;/property&gt;  
 &lt;/bean&gt;

    这个标签是我们在外部调用getBean("")方法的标签，那如果我有2个对象，在传入该标签ID的时候，Spring怎么知道我们需要获得的是哪个对象呢？为了解决这个问题，我们在外部多加上两个标签：

&lt;bean id="supersnoopy" parent="template"&gt;  
  &lt;property name="target" ref="snoopy"&gt;&lt;/property&gt;  
 &lt;/bean&gt;  
 &lt;bean id="superkitty" parent="template"&gt;  
  &lt;property name="target" ref="kitty"&gt;&lt;/property&gt;  
 &lt;/bean&gt;

    细心观察不难发现，这个就像是JAVA中的继承，parent属性指明该标签的父标签是谁，这样我们外部调用的时候就直接使用这两个子类的ID就能区分开了，由于我们把目标对象放到了子类中，则在父类中就不需要确定目标的标签了，不过因为父类不能被实例，所以我们需要给父类加上abstract="true"属性。

 

当然除了使用Spring的拦截器外，我们也可以自己定以一个拦截器类，只需要继承StaticMethodMatcherPointcutAdvisor，重写public boolean matches(Method method, Class targetClass) 方法，在方法里写上我们需要的规则。在xml文件中，由于匹配规则写到了拦截器类中，那我们就不需要配置了，并把类地址改成我们定义的类地址即可，如：

&lt;bean id="myInterceptor" class="com.lovo.interceptor.DogInterceptor"&gt;  
  &lt;property name="advice" ref="openMouth"&gt;&lt;/property&gt;  
 &lt;/bean&gt;

 

Spring为我们提供了4种代理，方法前、方法后、环绕、异常。

    方法前和方法后一样，就不再讲了。

    所谓环绕意思就是在一个方法中将之前，之后，执行方法（arg0.proceed();）一起写完，但要注意，如果方法有返回值，返回的值并不是在外部调用的地方返回，而是返回到环绕中的调用方法处，即arg0.proceed();的地方，如果我们想要在外部也能看见返回的值，需要在环绕中return （arg0.proceed();的值）。

    异常也是我们异常用到的，这个很简单，不需要我们修改配置，只需要写一个类继承Exception，重写里面的构造方法：

public class DogException extends Exception {

    public DogException() {  
  super();  
 }

 public DogException(Exception ex) {  
  super(ex);  
 }

 public DogException(Throwable th) {  
  super(th);  
 }

 public DogException(String message) {  
  super(message);  
 }

}

    然后在Advice类中实现ThrowsAdvice接口，重写public void afterThrowing(DogException de)方法，这个方法里面就写上异常的信息之类的东西，然后在外部调用方法的时候就可以直接捕获DogException异常了。很HIGH皮。