转自:http://zywang.iteye.com/blog/974226
使用@AspectJ标签
- 在配置文件中添加<aop:aspectj-autoproxy/>注解
- 创建一个Java文件,使用@Aspect注解修饰该类
- 创建一个方法,使用@Before、@After、@Around等进行修饰,在注解中写上切入点的表达式
说明:上述Java文件创建好后,需要将其在Spring的容器中进行声明,可以在配置文件中定义<bean/>节点,也可以使用@Component组件进行修饰
示例:
- importorg.aspectj.lang.ProceedingJoinPoint;
- importorg.aspectj.lang.annotation.After;
- importorg.aspectj.lang.annotation.AfterThrowing;
- importorg.aspectj.lang.annotation.Around;
- importorg.aspectj.lang.annotation.Aspect;
- importorg.aspectj.lang.annotation.Before;
- importorg.springframework.stereotype.Component;
- /**
- *基于注解的AOP日志示例
- *@authorZYWANG2011-3-24
- */
- @Component
- @Aspect
- publicclassAopLog{
- //方法执行前调用
- @Before("execution(*com.zywang.services.impl.*.*(..))")
- publicvoidbefore(){
- System.out.println("before");
- }
- //方法执行后调用
- @After("execution(*com.zywang.services.impl.*.*(..))")
- publicvoidafter(){
- System.out.println("after");
- }
- //方法执行的前后调用
- @Around("execution(*com.zywang.services.impl.*.*(..))")
- publicObjectaround(ProceedingJoinPointpoint)throwsThrowable{
- System.out.println("beginaround");
- Objectobject=point.proceed();
- System.out.println("endaround");
- returnobject;
- }
- //方法运行出现异常时调用
- @AfterThrowing(pointcut="execution(*com.zywang.services.impl.*.*(..))",throwing="ex")
- publicvoidafterThrowing(Exceptionex){
- System.out.println("afterThrowing");
- System.out.println(ex);
- }
- }
上面这段代码中多次使用了重复的切入点,这种情况下,可以使用@Pointcut标注,来修改一个切入点方法(这个方法不需要参数和方法体),然后就可以在@Before等标注中引用该方法作为切入点,示例如下:
- importorg.aspectj.lang.ProceedingJoinPoint;
- importorg.aspectj.lang.annotation.Around;
- importorg.aspectj.lang.annotation.Aspect;
- importorg.aspectj.lang.annotation.Before;
- importorg.aspectj.lang.annotation.Pointcut;
- importorg.springframework.stereotype.Component;
- /**
- *基于注解的AOP日志示例
- *@authorZYWANG2011-3-24
- */
- @Component
- @Aspect
- publicclassAopLog{
- @Pointcut("execution(*com.iflysse.school.services.impl.*.*(..))")
- publicvoidpointcut(){}
- //方法执行前调用
- @Before("pointcut()")
- publicvoidbefore(){
- System.out.println("before");
- }
- //方法执行的前后调用
- @Around("pointcut()")
- publicObjectaround(ProceedingJoinPointpoint)throwsThrowable{
- System.out.println("beginaround");
- Objectobject=point.proceed();
- System.out.println("endaround");
- returnobject;
- }
- }