Spring学习笔记之AOP配置篇(二) xml配置

1、创建切面类

这个部分不需要多说,在工程的某一个包下创建一个类即可。不同于注解配置,此时你并不需要加入任何东西。比如

public class LoggingAspect {
	
	public void beforeMethod(JoinPoint joinPoint) {
		String methodName = joinPoint.getSignature().getName();
		List<Object> args = Arrays.asList(joinPoint.getArgs());
		System.out.println("The method " + methodName + " begins with " + args);
	}
	
	public void afterMethod(JoinPoint joinPoint) {
		String methodName = joinPoint.getSignature().getName();
		System.out.println("The method " + methodName + " ends.");
	}
	
	public void afterMethodReturning(JoinPoint joinPoint, Object result) {
		String methodName = joinPoint.getSignature().getName();
		System.out.println("The method " + methodName + " returned " + result);
	}
    
  	public void afterMethodThrowing(JoinPoint joinPoint, Exception e) {
		System.out.println("Exception throwed");
	}
  
	public Object aroundMethod(ProceedingJoinPoint joinPoint) {
		Object result = null;
		try {
			System.out.println("before");
			result = joinPoint.proceed();
			System.out.println("afterReturning");
		} catch (Throwable e) {
			e.printStackTrace();
			System.out.println("afterThrowing");
		}
		System.out.println("after");
		return result;
	}
}

2、在配置文件中配置aop

1)加入命名空间

在xml里面配置aop需要加入aop的配置空间

xmlns:aop="http://www.springframework.org/schema/aop"

在根节点下注明即可

2)导入bean

  • 首先导入关注点的bean

  • 然后导入切面的bean,比如

    <bean id="loggingAspect" class="spring.aop.xml.LoggingAspect"></bean>
    

    (这里的class路径只是我测试使用的类路径,具体可自行设置,依旧是包名 + 类名

3)创建aop配置

创建aop配置不同于之前使用注解配置时使用的那个xml节点,此时我们应使用aop:config节点

  1. 创建aop:config节点

    <aop:config>
      <!-- slot(别多想,这只是一个注释) -->
    </aop:config>
    
  2. 创建一个切点表达式

    这里使用切点表达式的原因和使用注解配置的原因是一样的,为了简单。在上面的slot下面加上以下内容

    <!-- 配置切点表达式 -->
    <aop:pointcut expression="execution(public int spring.aop.xml.ArithmeticCalculatorImpl.*(int, int))" id="pointcut"/>
    

    这里使用了aop:pointcut节点,expression的值和之前的含义是一样的,id指明了切点的唯一标识

  3. 创建切面

    在上面的内容下再加上以下内容

    <aop:aspect ref="loggingAspect" order="1"></aop:aspect>
    

    这里的ref指的是在我们前面创建的bean里的哪一个来作为切面的,而order自然与注解配置里的含义是一样的,说明了切面执行的顺序

  4. 创建通知

    <aop:before method="beforeMethod" pointcut-ref="pointcut"/>
    <aop:after method="afterMethod" pointcut-ref="pointcut"/>
    <aop:after-returning method="afterMethodReturning" pointcut-ref="pointcut" returning="result"/>
    <aop:after-throwing method="afterMethodThrowing" pointcut-ref="pointcut" throwing="e"/>
    

    这里的method指定了我们创建的切面里的哪一个方法来作为通知方法,pointcut-ref则代表的是我们之前创建的哪一个切点(当然说的是多个切点的情况了)

    !在返回通知的配置中,returning代表了返回结果所代表的参数的参数名,在上面的类中可以看到,我指定了参数名为result

    !在异常通知的配置中,throwing则代表了抛出的异常的参数名
    !至于环绕通知的配置,与上面大同小异,不做赘述

posted @ 2017-08-11 11:10  风如杨  阅读(186)  评论(0)    收藏  举报