日期:2014-05-17  浏览次数:20996 次

spring切面(aspect)配置

1、切面类定义

?

package login.aop;

import org.aspectj.lang.JoinPoint;


public class AspectTest  {
	//该方法中可加参数也可不加,如果加了第一个时切入点
	public void before(JoinPoint joinPoint){
		//获得拦截的类
		String className = joinPoint.getClass().getName();
		//获得拦截的方法
		String methodName = joinPoint.getSignature().getName();
		//joinPoint.getSourceLocation().
		
		System.out.println("before-----------"+className+"   "+methodName);
	}
	public void after(){
		System.out.println("after-----------");
	}
}

?

?2、配置bean.xml

?

<bean id="userAdvice" class="login.aop.AspectTest">
	</bean>
	
	<aop:config>
		<aop:aspect id="userAspect" ref="userAdvice">
			<aop:pointcut id="myMethod"
                      expression="execution(public * login.service.impl.*.*(..))" />
            <aop:before method="before" pointcut-ref="myMethod"/>
            <aop:after-returning method="after" pointcut-ref="myMethod"/>			
		</aop:aspect>
	</aop:config>

?

expression是匹配的方法特征,aop:before/after-returning必须与定义的切面类中的方法名一致, 注意xml的命名空间引用

?

<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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/tx  
	http://www.springframework.org/schema/tx/spring-tx-2.5.xsd  
	http://www.springframework.org/schema/aop  
	http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
>

?3、测试类

package login.test;

import login.service.UserService;

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

public class MyAsp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml");
		UserService service = (UserService) context.getBean("userService");
		service.list();
		service.login("ligson", "admin");
		//service.login("ligson", null);
	}

}
?

?

4、常用切入点表达式总结

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
除了返回类型模式(上面代码片断中的ret-type-pattern),名字模式和参数模式以外,所有的部分都是可选的。 返回类型模式决定了方法的返回类型必须依次匹配一个连接点。 你会使用的最频繁的返回类型模式是 *,它代表了匹配任意的返回类型。 一个全称限定的类型名将只会匹配返回给定类型的方法。名字模式匹配的是方法名。 你可以使用 * 通配符作为所有或者部分命名模式。 参数模式稍微有点复杂:() 匹配了一个不接受任何参数的方法, 而 (..) 匹配了一个接受任意数量参数的方法(零或者更多)。 模式 (*) 匹配了一个接受一个任何类型的参数的方法。 模式 (*,String) 匹配了一个接受两个参数的方法,第一个可以是任意类型,第二个则必须是String类型。
下面给出一些常见切入点表达式的例子。
任意公共方法的执行:
execution(public * *(..))
任何一个以“set”开始的方法的执行:
execution(* set*(..))
AccountService 接口的任意方法的执行:
execution(* com.xyz.service.AccountService.*(..))
定义在service包里的任意方法的执行:
execution(* com.xyz.service.*.*(..))
定义在service包或者子包里的任意方法的执