Spring AOP之使用注解方式声明切入点的例子

在了解切入点之前不得不选了解连接点,什么是连接点

连接点(join point):它是指应用中执行的某个点,即程序执行流程中的某个点。如执行某个语句或者语句块、执行某个某方法、装载某个类、抛出某个异常 ......

切入点(pointcut):切入点是连接点的集合。它通常和"通知"联系在一起,是切面和程序流程的交叉点。例如:定义了这样一个切入点,它将某个方法和某个“通知”联系起来,那么程序执行过程中,当该方法执行时,则相应的“通知”将会被触发执行

spring的切入点表达式 execution([可见性] 返回类型 [声明类型].方法名(参数)[异常])

可见性:可选项。java类的方法、字段成员都有可见性,如 public、private、protected。使用"*"通配符匹配所有的可见性。

返回类型:必选项。可以用它匹配连接点方法的返回类型,如void String Object等,用"*"通配符可以匹配所有的返回类型。

声明类型:可选项。用于匹配java包,可用"*"、"+"等通配符。

方法名:必选项。用于匹配连接点方法名,可以使用"*"通配符。

参数:必选项。指定连接点的参数类型及个数,".."通配符匹配任何可能的情况。

异常:可选项。用于匹配连接点抛出异常的类型。

example:

MyAspectJ类定义Before切入点, 该切入点将匹配 com.laoyangx.bean.chapter11包和其子包中任何方法

MyAspectJ.java

package com.laoyangx.bean.chapter11;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MyAspectJ {
 /*
  * 以下都是正确的切入点表达式
  @Pointcut("execution(* AspectJTestBean.*(..))")
  @Pointcut("execution(void com.laoyangx.bean.chapter11.*.*(..))")
  @Pointcut("execution(* com.laoyangx.bean.chapter11..*.*(..))")	
  @Pointcut("execution(* com.laoyangx.bean.chapter11.AspectJTestBean.*(..))")
*/	
  @Pointcut("execution(* com.laoyangx.bean.chapter11..*(..))")
 public void Before(){}
 
 @Before("Before()")
 public void BeforeAspectJTestBean(JoinPoint point){
	 
	 AspectJTestBean aspectj=(AspectJTestBean)point.getTarget();
	 
	 System.out.println(aspectj.getClass().getName()+"."
			 +point.getSignature().getName()+"(),将要运行!");
 }	
}

AspectJTestBean.java

package com.laoyangx.bean.chapter11;

public class AspectJTestBean {

 public void MyMethod(){
	 System.out.println(this.getClass().getName()+
			 ".MyMethod() is run!");
 }		
}

spring bean 配置文件

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

<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="aspectj" class="com.laoyangx.bean.chapter11.AspectJTestBean"/>
<bean id="myaspectj" class="com.laoyangx.bean.chapter11.MyAspectJ"/>
</beans>

主程序:

ApplicationContext ctx=
			new ClassPathXmlApplicationContext("com/laoyangx/bean/chapter11/aspectjtestbean.xml");
	    
	    AspectJTestBean aspectj=(AspectJTestBean)ctx.getBean("aspectj");
	    aspectj.MyMethod();



posted @ 2011-10-15 21:14  来自非洲大草原的食人虎  阅读(4685)  评论(0)    收藏  举报