Spring(十二)AspectJ框架开发AOP(基于注解)

来源:互联网 发布:淘宝女装店铺标志图片 编辑:程序博客网 时间:2024/05/22 20:02

在上篇文章中( Spring(十一)AspectJ框架开发AOP(基于xml))是使用xml对AspectJ的使用,@AspectJ 是AspectJ1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面,所以可以使用xml方式和注解方式来开发AOP 所以在这篇文章中我们使用注解来代替xml。
我们可以使用注解一点一点替换xml的配置。
说明:

@Aspect 声明切面,修饰切面类,从而获得 通知。
通知
@Before 前置
@AfterReturning 后置
@Around 环绕
@AfterThrowing 抛出异常
@After 最终
切入点
@PointCut ,修饰方法 private void xxx(){} 之后通过“方法名”获得切入点引用

替换bean

在xml中

<!-- 创建目标类 -->    <bean id="userServiceId" class="com.scx.xmlproxy.test.UserServiceImpl"></bean>     <!-- 创建切面类(通知) -->      <bean id="myAspectId" class="com.scx.xmlproxy.test.MyAspect"></bean>  

我们知道xml中的bean可以使用注解@component来替换
在web开发中@component衍生了三个注解,我们也可以为不同的层次使用不同的注解。

web开发,提供3个@Component注解衍生注解(功能一样)
@Repository :dao层
@Service:service层
@Controller:web层
这三个注解和@Component一样,在web开发中使用这三个注解使代码更加清晰明了。
替换结果如下:
对于目标类,即service层
这里写图片描述
对于切面类
这里写图片描述

替换AOP

<aop:aspect ref="myAspectId">

这里写图片描述

替换公共切入点

xml配置:

    <aop:pointcut expression="execution(*com.scx.xmlproxy.test.*.*(..))" id="myPointCut"/>

注解替换:
需要在一个私有的方法上面添加注解@Pointcut。引用时就使用方法名称pointCut。
这里写图片描述

替换前置通知

xml配置:

<aop:before method="before" pointcut-ref="myPointCut"/>

注解替换:
在方法名上面添加@before注解

//前置通知    @Before(value = "pointCut()")    public void before(JoinPoint joinPoint){        System.out.println("MyAspect-before");    }

替换最终通知

xml代码

<aop:after method="after" pointcut-ref="myPointCut"/>

注解替换

    //最终通知    @After(value="pointCut()")    public void after(JoinPoint joinPoint){        System.out.println("MyAspect-after");    }

替换后置通知

xml配置:

<aop:after-returning method="afterReturning" pointcut-ref="myPointCut" returning="ret" />

注解替换:

//后置通知    @AfterReturning(value="pointCut()",returning="ret")    public void afterReturning(JoinPoint joinPoint,Object ret){        System.out.println("MyAspect-afterReturning  "+joinPoint.getSignature().getName()+"\t"+ret);    }

替换环绕通知

xml配置:

 <aop:around method="around" pointcut-ref="myPointCut"/>    

注解替换:

//环绕通知    @Around(value = "pointCut()")    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{        System.out.println("MyAspect-around-前");        Object obj=joinPoint.proceed();//执行目标方法        System.out.println("MyAspect-around-后");        return obj;    }

替换异常通知

xml配置:

<aop:after-throwing method="afterThrowing" pointcut-ref="myPointCut" throwing="e"/>

注解替换:

//异常通知    @AfterThrowing(value="pointCut()")    public void afterThrowing(JoinPoint joinPoint,Throwable e){        System.out.println("MyAspect-afterThrowing "+e.getMessage());    }

测试代码和上篇一样 运行结果也是一样。

1 0