AOP五种增强执行时机及@around增强注意事情

AOP的执行时机,一共有五个。分别为前置增强befor,后置增强after,返回后增强afterRunturning,异常后增强afterThorwing,环绕增强around

 

正如他们的名字一样,前置增强是在目标方法执行之前执行,后置增强在目标方法执行之后执行,返回后增强在目标方法执行return之后执行,异常增强则是在目标方法抛出异常后执行,而环绕增强在它修饰的方法中可以同时实现以上所有增强。

前4个增强大致区别也就@后面跟哪个单词的事情。具体体验方法可以参考之前的那篇博客。我们重点看一下Around增强


	@Around(value = "execution(public int com.jd.CalculatorService.*(..))")
	public Object around (ProceedingJoinPoint joinPoint) {
		Object result = null;
		Object target = joinPoint.getTarget();
		String methodName = joinPoint.getSignature().getName();
		
		try {
			try {//前置增强
				System.out.println(target.getClass().getName()+": The"+methodName+"method begins");
	
				result = joinPoint.proceed();
			} finally {//后置增强
				System.out.println(target.getClass().getName()+":The "+methodName+" method ends.");
			}
                //返回增强
                System.out.println(target.getClass().getName()+":Result of the "+methodName+" method:"+result);
		} catch (Throwable e) {//异常增强
			System.out.println(target.getClass().getName()+":Exception of the method "+methodName+": "+e);
		}		
		return result;
	}

around包含的4个增强已经在上面标注了出来。

需要注意的是@Before、@After、@AfterRunning和@AfterThrowing修饰的方法可以通过声明JoinPoint 类型参数变量获取目标方法的信息(方法名、参数列表等信息);@Around修饰的方法必须声明ProceedingJoinPoint类型的参数,该变量可以决定是否执行目标方法。

而中间的result = joinPoint.proceed();这一句是执行目标方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章