ITEEDU

采用静态配置方式实现AOP

静态配置时切面中只有通知,和正常JAVA类一样。切入点和关联通知都在配制文件中设置。

定义切面(Aspect)

package com.iteedu.spring;

public class SecurityHandler {

	private void checkSecurity() {
		System.out.println("----------checkSecurity()---------------");
	}
}

 

配制AOP

<?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"
	     xmlns:tx="http://www.springframework.org/schema/tx"
	     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
	<!-- Aspect类 -->
	<bean id="securityHandler" class="com.iteedu.spring.SecurityHandler"/>           
	<!-- 目标对象 -->
	<bean id="userManager" class="com.iteedu.spring.UserManagerImpl"/>
	<!--配制切入点和关联通知-->
	<aop:config>
		<aop:aspect id="security" ref="securityHandler">
			<aop:pointcut id="allAddMethod"
 expression="execution(* com.iteedu.spring.UserManagerImpl.add*(..))"/>
			<aop:before method="checkSecurity" pointcut-ref="allAddMethod"/>
		</aop:aspect>
	</aop:config>	
</beans>

AOP的配制都要放在<aop:config>标签中,其中可以定义多个切面(<aop:aspect >),每个切面中可以定义其包含的通知对应的切入点(<aop:pointcut />)。

<aop:config>
	<!—全局可见 -->
<aop:pointcut />
	<aop:aspect >
	    <!—切面可见 -->
		<aop:pointcut />
		<aop:before/>
	</aop:aspect>
    …
</aop:config>

目标对象和用注释实现时是一样的,可以参考采用Annotation注解方式实现AOP

切面定义

首先要将切面类定义成bean。

用<aop:aspect >的ref属性引用定义的bean。

通知定义

通知要放到对应切面的<aop:aspect >标签中。

每种类型通知都有自己的标签,不过所设置的属性相同。

用method定义通知是切面中的哪个方法。

用pointcut-ref定义通知要植入的切入点。

切入点定义

切入点用<aop:pointcut />标签定义。

定义一个id值用于通知的引用。

定义一个expression匹配一个方法集合用来植入通知。

expression中最常用的是execution切入点指定者,形如execution(public * *(..))。

其完整定义如下:

execution(修饰符?  返回类型  声明类型?  方法名模式(参数模式)  异常模式?)

其中带问号的为可选,其它为必须指定的。

  1. 使用 * 通配符作为所有或者部分命名模式。
  2. 模式() 匹配了一个不接受任何参数的方法
  3. 模式(..) 匹配了一个接受任意数量参数的方法(零或者更多)。
  4. 模式(*) 匹配了一个接受一个任何类型的参数的方法。
  5. 模式 (*,String) 匹配了一个接受两个参数的方法,第一个可以是任意类型,第二个则必须是String类型。

方法名模式是可以匹配路径的,如:

execution(* com.xyz.service..*.*(..))

定义在service包或者子包里的任意方法的执行。

execution(* com.xyz.service.*.*(..))

定义在service包里的任意方法的执行。