您的位置:首页 > 编程语言 > Java开发

Spring笔记4-AOP,前置通知,后置通知,返回通知,异常通知

2017-08-27 19:20 597 查看
<beans>
<!--配置自动扫描的包-->
<context:componemt-scan base-package="com.kcj.test"></context:componemt-scan>

<!--使用Aspectj注解,自动为匹配的类生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>


package com.kcj.test;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(1)//设置切面的优先级,数字越小优先级越高
@Aspect//声明为一个切面
@Component//放到IOC容器
public class LoggingAspect {

/***
* 定义一个方法来声明切入点,提供引用
*/
@Pointcut("execution(* com.kcj.test.*.*(..))")
public void declareJoinPointExxcution(){
}

/***
* 声明该方法是一个前置通知,方法执行之前执行
*/
@Before("LoggingAspect.declareJoinPointExxcution()")
public void before(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
}

/***
* 声明该方法是一个后置通知,目标方法执行后执行,就算目标方法抛出异常也会执行
* 但是后置通知不能访问目标方法返回的结果
*/
@Before("declareJoinPointExxcution()")
public void after(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
}

/***
* 在目标方法正常执行完了之后执行,可以访问到方法的返回值:result
*/
@AfterReturning(value = "declareJoinPointExxcution()", returning = "result")
public void afterReturning(JoinPoint joinPoint, Object result) {
}

/***
* 在目标方法抛出异常执行,也可以指定出现制定异常时执行,Exception改为需要指定的一场类型
*/
@AfterThrowing(value = "execution(* com.kcj.test.*.*(..)))",throwing = "e")
public void afterThorwing(JoinPoint joinPoint, Exception e) {
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐