Spring AOP

来源:互联网 发布:下载淘宝网app 编辑:程序博客网 时间:2024/05/29 13:18

Spring AOP

AOP(Aspect-Oriented Programming)面向切面编程。
切面(Aspect):横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象。
通知(Advice):切面必须要完成的工作
目标(Target):被通知的对象
代理(Proxy):向目标对象应用通知之后创建的对象
连接点(Joinpoint):程序执行的某个特定位置
切点(pointcut):连接点相当于数据库中的记录,切点相当于查询条件。

在Spring2.0以上版本中,可以使用基于AspectJ注解或基于XML配置的AOP。AspectJ是Java社区里最完整最流行的AOP框架。

在Spring中启用AspectJ注解支持

要在Spring应用中使用AspectJ注解,必须在classpath下包含AspectJ类库:aopalliance.jaraspectj.weaver.jarspring-aspects.jar。全部的包如下:
aop的包

将aop Schema添加到<beans>根元素中。

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

基于注解的方法,在配置文件中加入如下的配置:

<!-- 使AspectJ注解起作用:自动匹配类生产代理对象 --><aop:aspectj-autoproxy></aop:aspectj-autoproxy>

配置文件的完整代码:

<?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:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">    <!-- 配置自动扫描的包 -->    <context:component-scan base-package="aop.impl"></context:component-scan>    <!-- 使AspectJ注解起作用:自动匹配类生产代理对象 -->    <aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>

把横切关注点的代码抽象到切面类中

  1. 切面首先是一个IoC的bean,即加入@Component注解
  2. 切面还需要加入@Aspect注解
  3. 在类中声明各种通知

通知

这个例子的主要功能是在调用某个方法前后输出日志

把某个类声明为一个切面

  • 需要把该类放入到IoC容器中,可以使用@Component注解
  • 在声明一个切面,可以使用@Aspect注解

前置通知

声明方法是一个前置通知:在目标方法开始之前执行
如下所示

@Before("execution(public int aop.impl.AthimeticCalculator.add(int, int))")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);}

作用于AthimeticCalculatoradd方法

如果想作用于AthimeticCalculator下的所有方法,可以使用*

@Before("execution(public int aop.impl.AthimeticCalculator.*(int, int))")

完整代码如下:

package aop.impl;import java.util.Arrays;import java.util.List;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.springframework.stereotype.Component;@Aspect@Componentpublic class LoggingAspect {    @Before("execution(public int aop.impl.AthimeticCalculator.*(int, int))")    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);    }}

后置通知

后置通知在目标方法执行后(无论是否发生异常),执行通知。
在后置方法中还不能访问目标方法执行的结果。

@After("execution(* aop.impl.*.*(int, int)) )")public void afterMethod(JoinPoint joinpoint) {    String methodName = joinpoint.getSignature().getName();    List<Object> args = Arrays.asList(joinpoint.getArgs());    System.out.println("The method "+methodName +" ends with "+args);}

返回通知

在方法正常结束后执行的代码,返回通知是可以访问到方法的返回值的。

@AfterReturning(value="execution(* aop.impl.*.*(int, int)))", returning="result")public void afterReturning(JoinPoint joinPoint, Object result ) {    String methodName = joinPoint.getSignature().getName();    System.out.println("The method "+methodName +" return with "+result);}

异常通知

在方法出现异常时会执行的代码,可以访问到异常的对象,且可以指定在出现特定异常时在执行通知代码

@AfterThrowing(value="execution(* aop.impl.*.*(int, int)))", throwing="ex")public void afterThrowing(JoinPoint joinPoint, Exception ex) {    String methodName = joinPoint.getSignature().getName();    System.out.println("The method "+methodName +" throw with "+ex);}

环绕通知

环绕通知需要携带ProceedingJoinPoint类型的参数。环绕通知类似于动态代理的全过程,ProceedingJoinPoint类型的参数可以决定是否执行目标方法。且环绕通知必须有返回值,返回值即为目标方法的返回值。

@Around("execution(* aop.impl.*.*(int, int)))")public Object around(ProceedingJoinPoint pjd) {    System.out.println("around");    Object result = null;    String methodName = pjd.getSignature().getName();    //执行目标方法    try {        //前置通知        System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));        result = pjd.proceed();        //后置通知        System.out.println("The method "+methodName +" ends with "+Arrays.asList(pjd.getArgs()));    } catch (Throwable e) {        //异常通知        e.printStackTrace();    }    //后置通知    return result;}

优先级
使用@Order注解指定切面的优先级,值越小优先级越高

@Order(1)@Aspect@Componentpublic class ValidationAspect {    @Before("execution(* aop.impl.*.*(..))")    public void validateArgs(JoinPoint joinPoint) {        System.out.println("validate:" + Arrays.asList(joinPoint.getArgs()));    }}

重用切点表达式
@Pointcut来声明切入点表达式,后面的其他通知直接使用方法名来引用当前的切入点表达式。

    /**     * 定义一个方法,用于声明切入点表达式     * 一般的,该方法中不需要添入其他的代码     */    @Pointcut("execution(public int aop.impl.AthimeticCalculator.*(int, int))")    public void declareJointPoinExpression() {}    @Before("declareJointPoinExpression()")    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);}

Spring基于配置文件的方式来配置AOP

Spring也支持在Bean配置文件中声明切面。这种声明是通过aop schema中的XML元素完成的。
正常情况下,基于注解的声明要优于基于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.xsd        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">    <!-- 配置Bean -->    <bean id="athimeticCalculator" class="aop.impl.xml.AthimeticCalculatorImpl"></bean>    <!-- 配置切面的bean -->    <bean id="loggingAspect" class="aop.impl.xml.LoggingAspect"></bean>    <bean id="validationAspect" class="aop.impl.xml.ValidationAspect"></bean>    <!-- 配置AOP -->    <aop:config>        <!-- 配置切点表达式 -->        <aop:pointcut expression="execution(* aop.impl.xml.*.*(..))" id="pointcut"/>        <!-- 配置切面及通知 -->        <aop:aspect ref="loggingAspect" order="2">            <aop:before method="beforeMethod" pointcut-ref="pointcut"/>            <aop:after method="afterMethod" pointcut-ref="pointcut"/>        </aop:aspect>        <aop:aspect ref="validationAspect" order="1">            <aop:before method="validateArgs" pointcut-ref="pointcut"/>        </aop:aspect>    </aop:config></beans>
0 0