05-Spring3 AOP B_基于Schema的AOP

前面我们对Spring AOP有了个入门,今天来整理一下基于SchemaAOP。基于SchemaAOPSpring2.0之后通过“aop”命名空间来定义切面、切入点及声明通知。

         Spring配置文件中,所有AOP相关定义必须放在<aop:config>标签下,该标签下可以有<aop:pointcut><aop:advisor><aop:aspect>标签,配置顺序不可变。

<aop:pointcut>:用来定义切入点,该切入点可以重用;

<aop:advisor>:用来定义只有一个通知和一个切入点的切面;

<aop:aspect>:用来定义切面,该切面可以包含多个切入点和通知,而且标签内部的通知和切入点定义是无序的;和advisor的区别就在此,advisor只包含一个通知和一个切入点。

 

 

一、声明切面

         切面就是包含切入点和通知的对象,在Spring容器中将被定义为一个BeanSchema方式的切面需要一个切面支持Bean,该支持Bean的字段和方法提供了切面的状态和行为信息,并通过配置方式来指定切入点和通知实现。

    切面使用<aop:aspect>标签指定,ref属性用来引用切面支持Bean

    切面支持BeanaspectSupportBean”跟普通Bean完全一样使用,切面使用“ref”属性引用它。

 

二、声明切入点

 

切入点在Spring中也是一个BeanBean定义方式可以有三种方式:

 

1、在<aop:config>标签下使用<aop:pointcut>声明一个切入点Bean

 

         该切入点可以被多个切面使用,对于需要共享使用的切入点最好使用该方式,该切入点使用id属性指定Bean名字,在通知定义时使用pointcut-ref属性通过该id引用切入点,expression属性指定切入点表达式:

<aop:config>
		<aop:pointcut id="pointcut" expression="execution(* com.iflytek..*.*(..))" />
		<aop:aspect ref="aspectSupportBean">
			<aop:before pointcut-ref="pointcut" method="before" />
		</aop:aspect>
	</aop:config>

 

2、在<aop:aspect>标签下使用<aop:pointcut>声明一个切入点Bean

         该切入点可以被多个切面使用,但一般该切入点只被该切面使用,当然也可以被其他切面使用,但最好不要那样使用,该切入点使用id属性指定Bean名字,在通知定义时使用pointcut-ref属性通过该id引用切入点,expression属性指定切入点表达式:

<aop:config>
		<aop:aspect ref="aspectSupportBean">
			<aop:pointcut id=" pointcut" expression="execution(* com.iflytek..*.*(..))" />
			<aop:before pointcut-ref="pointcut" method="before" />
		</aop:aspect>
	</aop:config>

 

3、匿名切入点Bean

可以在声明通知时通过pointcut属性指定切入点表达式,该切入点是匿名切入点,只被该通知使用:

	<aop:config>
		<aop:aspect ref="aspectSupportBean">
			<aop:after pointcut="execution(* com.iflytek..*.*(..))"
				method="afterFinallyAdvice" />
		</aop:aspect>
	</aop:config>

 

三、声明通知

 

基于Schema方式支持前边介绍的5中通知类型:

 

1、前置通知

 

在切入点选择的方法之前执行,通过<aop:aspect>标签下的<aop:before>标签声明:

	<aop:before pointcut="切入点表达式" pointcut-ref="切入点Bean引用"
		method="前置通知实现方法名" arg-names="前置通知实现方法参数列表参数名字" />

pointcutpointcut-ref二者选一,指定切入点; 

    method指定前置通知实现方法名,如果是多态需要加上参数类型,多个用隔开,如beforeAdvice(java.lang.String)

       arg-names指定通知实现方法的参数名字,多个用分隔,可选,类似于前面说的构造器注入中的参数名注入限制:class文件中没生成变量调试信息是获取不到方法参数名字的,因此只有在类没生成变量调试信息时才需要使用arg-names属性来指定参数名,如arg-names="param"表示通知实现方法的参数列表的第一个参数名字为“param”

 

2、后置返回通知

 

在切入点选择的方法正常返回时执行,通过<aop:aspect>标签下的<aop:after-returning>标签声明:

<aop:after-returning pointcut="切入点表达式"  pointcut-ref="切入点Bean引用"
    method="后置返回通知实现方法名"
    arg-names="后置返回通知实现方法参数列表参数名字"
    returning="返回值对应的后置返回通知实现方法参数名"/>

pointcutpointcut-refmethodarg-names同前置通知同义;

       returning定义一个名字,该名字用于匹配通知实现方法的一个参数名,当目标方法执行正常返回后,将把目标方法返回值传给通知方法;returning限定了只有目标方法返回值匹配与通知方法相应参数类型时才能执行后置返回通知,否则不执行,对于returning对应的通知方法参数为Object类型将匹配任何目标返回值。

 

3、后置异常通知

 

在切入点选择的方法抛出异常时执行,通过<aop:aspect>标签下的<aop:after-throwing>标签声明:

<aop:after-throwing pointcut="切入点表达式"  pointcut-ref="切入点Bean引用"
                        method="后置异常通知实现方法名"
                        arg-names="后置异常通知实现方法参数列表参数名字"
                        throwing="将抛出的异常赋值给的通知实现方法参数名"/>

pointcutpointcut-refmethodarg-names同前置通知同义;

throwing定义一个名字,该名字用于匹配通知实现方法的一个参数名,当目标方法抛出异常返回后,将把目标方法抛出的异常传给通知方法;throwing限定了只有目标方法抛出的异常匹配与通知方法相应参数异常类型时才能执行后置异常通知,否则不执行,对于throwing对应的通知方法参数为Throwable类型将匹配任何异常。

 

4、后置最终通知

 

         在切入点选择的方法返回时执行,不管是正常返回还是抛出异常都执行,通过<aop:aspect>标签下的<aop:after >标签声明:

	<aop:after pointcut="切入点表达式"  pointcut-ref="切入点Bean引用"
                  method="后置最终通知实现方法名"
                  arg-names="后置最终通知实现方法参数列表参数名字"/>

 

5、环绕通知

 

环绕着在切入点选择的连接点处的方法所执行的通知,环绕通知非常强大,可以决定目标方法是否执行,什么时候执行,执行时是否需要替换方法参数,执行完毕是否需要替换返回值,可通过<aop:aspect>标签下的<aop:around >标签声明:

<aop:around pointcut="切入点表达式"  pointcut-ref="切入点Bean引用"
                     method="后置最终通知实现方法名"
                     arg-names="后置最终通知实现方法参数列表参数名字"/>

 环绕通知第一个参数必须是org.aspectj.lang.ProceedingJoinPoint类型,在通知实现方法内部使用ProceedingJoinPointproceed()方法使目标方法执行,proceed 方法可以传入可选的Object[]数组,该数组的值将被作为目标方法执行时的参数。

 

Demo

 

IHelloWorldService.java

	package com.iflytek.service;

/**
 * @author xdwang
 * 
 * @create 2013-8-9 下午7:46:28
 * 
 * @email:[email protected]
 * 
 * @description 目标接口
 * 
 */
public interface IHelloWorldService {

	/**
	 * @descrption 前置通知
	 * @author xdwang
	 * @create 2013-8-9下午7:27:41
	 * @param param
	 */
	public void sayBefore(String param);

	/**
	 * @descrption 后置返回通知
	 * @author xdwang
	 * @create 2013-8-9下午7:27:53
	 * @return
	 */
	public boolean sayAfterReturning();

	/**
	 * @descrption 后置异常通知
	 * @author xdwang
	 * @create 2013-8-9下午7:33:04
	 */
	public void sayAfterThrowing();

	/**
	 * @descrption 后置最终通知
	 * @author xdwang
	 * @create 2013-8-9下午7:39:21
	 * @return
	 */
	public boolean sayAfterFinally();
	
	/**
	 * @descrption 环绕通知
	 * @author xdwang
	 * @create 2013-8-9下午7:44:47
	 * @param param
	 */
	public void sayAround(String param);  
}

 

HelloWorldService.java

package com.iflytek.service.impl;

import com.iflytek.service.IHelloWorldService;

/**
 * @author xdwang
 * 
 * @create 2013-8-9 下午7:47:07
 * 
 * @email:[email protected]
 * 
 * @description 目标接口实现
 * 
 */
public class HelloWorldService implements IHelloWorldService {

	@Override
	public void sayBefore(String param) {
		System.out.println("============say " + param);
	}

	@Override
	public boolean sayAfterReturning() {
		System.out.println("============after returning");
		return true;
	}

	@Override
	public void sayAfterThrowing() {
		System.out.println("============before throwing");
		throw new RuntimeException();
	}

	@Override
	public boolean sayAfterFinally() {
		System.out.println("============before finally");
		throw new RuntimeException();
	}

	@Override
	public void sayAround(String param) {
		System.out.println("============around param:" + param);
	}
}

 

HelloWorldAspect.java

package com.iflytek.aop;

import org.aspectj.lang.ProceedingJoinPoint;

/**
 * @author xdwang
 * 
 * @create 2013-8-9 下午7:47:50
 * 
 * @email:[email protected]
 * 
 * @description 切面
 * 
 */
public class HelloWorldAspect {
	/**
	 * @descrption 前置通知
	 * @author xdwang
	 * @create 2013-8-9下午7:28:17
	 * @param param
	 */
	public void beforeAdvice(String param) {
		System.out.println("===========before advice param:" + param);
	}

	/**
	 * @descrption 后置返回通知
	 * @author xdwang
	 * @create 2013-8-9下午7:28:23
	 * @param retVal
	 */
	public void afterReturningAdvice(Object retVal) {
		System.out.println("===========after returning advice retVal:" + retVal);
	}

	/**
	 * @descrption 后置异常通知
	 * @author xdwang
	 * @create 2013-8-9下午7:33:41
	 * @param exception
	 */
	public void afterThrowingAdvice(Exception exception) {
		System.out.println("===========after throwing advice exception:" + exception);
	}

	/**
	 * @descrption 后置最终通知
	 * @author xdwang
	 * @create 2013-8-9下午7:39:55
	 */
	public void afterFinallyAdvice() {
		System.out.println("===========after finally advice");
	}
	
	/**
	 * @descrption 环绕通知
	 * @author xdwang
	 * @create 2013-8-9下午7:45:29
	 * @param pjp
	 * @return
	 * @throws Throwable
	 */
	public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
	    System.out.println("===========around before advice");
	    Object retVal = pjp.proceed(new Object[] {"replace"});
	    System.out.println("===========around after advice");
	    return retVal;
	}

}

 

Resources/advice.xml

<?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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	<bean id="helloWorldService" class="com.iflytek.service.impl.HelloWorldService" />
	<bean id="aspect" class="com.iflytek.aop.HelloWorldAspect" />
	<aop:config>
		<aop:aspect ref="aspect">
			<!-- 前置通知 -->
			<aop:before
				pointcut="execution(* com.iflytek..*.sayBefore(..)) and args(param)"
				method="beforeAdvice(java.lang.String)" arg-names="param" />

			<!-- 后置返回通知 -->
			<aop:after-returning
				pointcut="execution(* com.iflytek..*.sayAfterReturning(..))" method="afterReturningAdvice"
				arg-names="retVal" returning="retVal" />

			<!-- 后置异常通知 -->
			<aop:after-throwing
				pointcut="execution(* com.iflytek..*.sayAfterThrowing(..))" method="afterThrowingAdvice"
				arg-names="exception" throwing="exception" />

			<!-- 后置最终通知 -->
			<aop:after pointcut="execution(* com.iflytek..*.sayAfterFinally(..))"
				method="afterFinallyAdvice" />

			<!-- 环绕通知-->
			<aop:around pointcut="execution(* com.iflytek..*.sayAround(..))"
				method="aroundAdvice" />
			
		</aop:aspect>
	</aop:config>

</beans>

 

test 

package com.iflytek.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.iflytek.service.IHelloWorldService;

/**
 * @author xdwang
 * 
 * @create 2013-8-8 下午7:58:22
 * 
 * @email:[email protected]
 * 
 * @description 测试
 * 
 */
public class AopTest {

	/**
	 * @descrption 前置通知
	 * @author xdwang
	 * @create 2013-8-9下午7:27:19
	 */
	@Test
	public void testSchemaBeforeAdvice() {
		System.out.println("======================================");
		ApplicationContext ctx = new ClassPathXmlApplicationContext("advice.xml");
		IHelloWorldService helloworldService = ctx.getBean("helloWorldService", IHelloWorldService.class);
		helloworldService.sayBefore("before");
		System.out.println("======================================");
	}

	/**
	 * @descrption 后置返回通知
	 * @author xdwang
	 * @create 2013-8-9 下午7:27:06
	 */
	@Test
	public void testSchemaAfterReturningAdvice() {
		System.out.println("======================================");
		ApplicationContext ctx = new ClassPathXmlApplicationContext("advice.xml");
		IHelloWorldService helloworldService = ctx.getBean("helloWorldService", IHelloWorldService.class);
		helloworldService.sayAfterReturning();
		System.out.println("======================================");
	}

	/**
	 * @descrption 后置异常通知
	 * @author xdwang
	 * @create 2013-8-9下午7:35:48
	 */
	@Test(expected = RuntimeException.class)
	public void testSchemaAfterThrowingAdvice() {
		System.out.println("======================================");
		ApplicationContext ctx = new ClassPathXmlApplicationContext("advice.xml");
		IHelloWorldService helloworldService = ctx.getBean("helloWorldService", IHelloWorldService.class);
		helloworldService.sayAfterThrowing();
		System.out.println("======================================");
	}
	
	/**
	 * @descrption 后置异常通知
	 * @author xdwang
	 * @create 2013-8-9下午7:41:48
	 */
	@Test(expected = RuntimeException.class)
	public void testSchemaAfterFinallyAdvice() {
	    System.out.println("======================================");
	    ApplicationContext ctx = new ClassPathXmlApplicationContext("advice.xml");
	    IHelloWorldService helloworldService = ctx.getBean("helloWorldService", IHelloWorldService.class);
	    helloworldService.sayAfterFinally();
	    System.out.println("======================================");
	}
	
	/**
	 * @descrption 环绕通知
	 * @author xdwang
	 * @create 2013-8-9下午7:46:40
	 */
	@Test
	public void testSchemaAroundAdvice() {
	    System.out.println("======================================");
	    ApplicationContext ctx = new ClassPathXmlApplicationContext("advice.xml");
	    IHelloWorldService helloworldService =
	    ctx.getBean("helloWorldService", IHelloWorldService.class);
	    helloworldService.sayAround("haha");
	    System.out.println("======================================");
	}
}

 

结果:

1、前置通知
======================================
===========before advice param:before
============say before
2、后置通知
======================================
============after returning
===========after returning advice retVal:true
======================================
3、后置异常通知
======================================
============before throwing
===========after throwing advice exception:java.lang.RuntimeException
4、后置最终通知
======================================
============before finally
===========after finally advice
5、环绕通知
======================================
===========around before advice
============around param:replace
===========around after advice
======================================

 

分析一下吧:

 

前置通知:

 1)切入点匹配:在配置中使用“execution(* com.iflytek..*.sayBefore(..)) ”匹配目标方法sayBefore,且使用“args(param)”匹配目标方法只有一个参数且传入的参数类型为通知实现方法中同名的参数类型;

 2)目标方法定义:使用method=" beforeAdvice(java.lang.String) "指定前置通知实现方法,且该通知有一个参数类型为java.lang.String参数;

 3)目标方法参数命名:其中使用arg-names=" param "指定通知实现方法参数名为“param”,切入点中使用“args(param)”匹配的目标方法参数将自动传递给通知实现方法同名参数。

  

后置通知:

 1)切入点匹配:在配置中使用“execution(* com.iflytek..*.sayAfterReturning(..)) ”匹配目标方法sayAfterReturning,该方法返回true

 2)目标方法定义:使用method="afterReturningAdvice"指定后置返回通知实现方法;

 3)目标方法参数命名:其中使用arg-names="retVal"指定通知实现方法参数名为“retVal”

 4)返回值命名:returning="retVal"用于将目标返回值赋值给通知实现方法参数名为“retVal”的参数上。

  

后置异常通知:

 1)切入点匹配:在配置中使用“execution(* com.iflytek..*.sayAfterThrowing(..))”匹配目标方法sayAfterThrowing,该方法将抛出RuntimeException异常;

 2)目标方法定义:使用method="afterThrowingAdvice"指定后置异常通知实现方法;

 3)目标方法参数命名:其中使用arg-names="exception"指定通知实现方法参数名为“exception”

 4)异常命名:returning="exception"用于将目标方法抛出的异常赋值给通知实现方法参数名为“exception”的参数上。

  

后置最终通知:

 1)切入点匹配:在配置中使用“execution(* com.iflytek..*.sayAfterFinally(..))”匹配目标方法sayAfterFinally,该方法将抛出RuntimeException异常;

 2)目标方法定义:使用method=" afterFinallyAdvice "指定后置最终通知实现方法。

  

环绕通知:

 1)切入点匹配:在配置中使用“execution(* com.iflytek..*.sayAround(..))”匹配目标方法sayAround

 2)目标方法定义:使用method="aroundAdvice"指定环绕通知实现方法,在该实现中,第一个方法参数为pjp,类型为ProceedingJoinPoint,其中“Object retVal = pjp.proceed(new Object[] {"replace"});”,用于执行目标方法,且目标方法参数被“new Object[] {"replace"}”替换,最后返回“retVal ”返回值。

3)测试:我们使用“helloworldService.sayAround("haha");”传入参数为“haha”,但最终输出为“replace”,说明参数被替换了。

 

四、引入

 

             Spring引入允许为目标对象引入新的接口,通过在< aop:aspect>标签内使用< aop:declare-parents>标签进行引入,定义方式如下:

	<aop:declare-parents
          types-matching="AspectJ语法类型表达式"
          implement-interface=引入的接口"             
          default-impl="引入接口的默认实现"
          delegate-ref="引入接口的默认实现Bean引用"/>

 types-matching匹配需要引入接口的目标对象的AspectJ语法类型表达式;

 implement-interface定义需要引入的接口;

 default-impldelegate-ref定义引入接口的默认实现,二者选一,default-impl是接口的默认实现类全限定名,而delegate-ref是默认的实现的委托Bean名;

  

Demo

public void induct();

 

@Override
	public void induct() {
		System.out.println("=========introduction");
	}

 

<aop:declare-parents types-matching="com.iflytek..*.IHelloWorldService+"
				implement-interface="com.iflytek.service.IIntroductionService"
				default-impl="com.iflytek.service.impl.IntroductiondService" />

 

@Test
	public void testSchemaIntroduction() {
		System.out.println("======================================");
		ApplicationContext ctx = new ClassPathXmlApplicationContext("advice.xml");
		IIntroductionService introductionService = ctx.getBean("helloWorldService", IIntroductionService.class);
		introductionService.induct();
		System.out.println("======================================");
	}

 

======================================
=========introduction
======================================

 

分析一下吧:

 1)目标对象类型匹配:使用types-matching="com.iflytek..*.IHelloWorldService+"匹配IHelloWorldService接口的子类型,如HelloWorldService实现;

 2)引入接口定义:通过implement-interface属性表示引入的接口,如“cn.javass.service.IIntroductionService”

 3)引入接口的实现:通过default-impl属性指定,如“cn.javass.service.impl.IntroductiondService”,也可以使用“delegate-ref”来指定实现的Bean

 4)获取引入接口:如使用“ctx.getBean("helloWorldService", IIntroductionService.class);”可直接获取到引入的接口。

  

五、Advisor

 Advisor表示只有一个通知和一个切入点的切面,由于Spring AOP都是基于AOP联盟的拦截器模型的环绕通知的,所以引入Advisor来支持各种通知类型(如前置通知等5种),Advisor概念来自于Spring1.2AOP的支持,在AspectJ中没有相应的概念对应。

 

Advisor可以使用<aop:config>标签下的<aop:advisor>标签定义:

<aop:advisor pointcut="切入点表达式" pointcut-ref="切入点Bean引用"
                     advice-ref="通知API实现引用"/>

 pointcutpointcut-ref二者选一,指定切入点表达式;

 advice-ref引用通知API实现Bean,如前置通知接口为MethodBeforeAdvice

 

Demo:

	public void sayAdvisorBefore(String param);  

 

	@Override
	public void sayAdvisorBefore(String param) {
		System.out.println("============say " + param);
	}

 

第三定义前置通知API实现(BeforeAdviceImpl.java)

package com.iflytek.aop;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

/**
 * @author xdwang
 * 
 * @create 2013-8-9 下午8:00:34
 * 
 * @email:[email protected]
 * 
 * @description 第三定义前置通知API实现
 * 
 */
public class BeforeAdviceImpl implements MethodBeforeAdvice {
	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		System.out.println("===========before advice");
	}
}

 

<bean id="beforeAdvice" class="com.iflytek.aop.BeforeAdviceImpl" />

 

然后在<aop:config>标签下,添加Advisor定义,添加时注意顺序:

<!-- advisor -->
		<aop:advisor pointcut="execution(* com.iflytek..*.sayAdvisorBefore(..))"
			advice-ref="beforeAdvice" />

 

	@Test
	public void testSchemaAdvisor() {
		System.out.println("======================================");
		ApplicationContext ctx = new ClassPathXmlApplicationContext("advice.xml");
		IHelloWorldService helloworldService = ctx.getBean("helloWorldService", IHelloWorldService.class);
		helloworldService.sayAdvisorBefore("haha");
		System.out.println("======================================");
	}

 

======================================
===========before advice
============say haha
======================================

 

不推荐使用Advisor,除了在进行事务控制的情况下,其他情况一般不推荐使用该方式,该方式属于侵入式设计,必须实现通知API

 

  

转自http://jinnianshilongnian.iteye.com/

 

猜你喜欢

转载自xdwangiflytek.iteye.com/blog/1921711