spring-aop-@Aspect

Spring使用的AOP注解分为三个层次:

前提条件是在xml中放开了<aop:aspectj-autoproxy proxy-target-class="true"/><!-- 开启切面编程功能 -->

1、@Aspect放在类头上,把这个类作为一个切面。

2、 @Pointcut放在方法头上,定义一个可被别的方法引用的切入点表达式。

3、5种通知。

3.1、@Before,前置通知,放在方法头上。

3.2、@After,后置【finally】通知,放在方法头上。

3.3、@AfterReturning,后置【try】通知,放在方法头上,使用returning来引用方法返回值。

3.4、@AfterThrowing,后置【catch】通知,放在方法头上,使用throwing来引用抛出的异常。

3.5、@Around,环绕通知,放在方法头上,这个方法要决定真实的方法是否执行,而且必须有返回值。

@Component
@Aspect
public class LogAspect {

	/**
	 * 定义Pointcut,Pointcut的名称 就是simplePointcut,此方法不能有返回值,该方法只是一个标示
	 */
	@Pointcut("execution(public * com.service.impl..*.*(..))")
	public void recordLog() {
	}

	@AfterReturning(pointcut = "recordLog()")
	public void simpleAdvice() {
		LogUtil.info("AOP后处理成功 ");
	}

	@Around("recordLog()")
	public Object aroundLogCalls(ProceedingJoinPoint jp) throws Throwable {
		LogUtil.info("正常运行");
		return jp.proceed();
	}

	@Before("recordLog()")
	public void before(JoinPoint jp) {
		String className = jp.getThis().toString();
		String methodName = jp.getSignature().getName(); // 获得方法名
		LogUtil.info("位于:" + className + "调用" + methodName + "()方法-开始!");
		Object[] args = jp.getArgs(); // 获得参数列表
		if (args.length <= 0) {
			LogUtil.info("====" + methodName + "方法没有参数");
		} else {
			for (int i = 0; i < args.length; i++) {
				LogUtil.info("====参数  " + (i + 1) + ":" + args[i]);
			}
		}
		LogUtil.info("=====================================");
	}

	@AfterThrowing("recordLog()")
	public void catchInfo() {
		LogUtil.info("异常信息");
	}

	@After("recordLog()")
	public void after(JoinPoint jp) {
		LogUtil.info("" + jp.getSignature().getName() + "()方法-结束!");
		LogUtil.info("=====================================");
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值