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

Spring基础---AOP使用拓展

2017-11-17 15:37 309 查看

一、使用注解定义切面

1、定义切面



2、在spring配置文件启用 aspectj 注解

<!-- 在头文件引入 aop xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd" -->
<!-- 生成一个增强类的实例 -->
<bean id="advice" class="advice.UserAdvice"></bean>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>


3、使用注解定义其他 增强

//使用注解 配置异常抛出增强   参数是切入点,抛出的异常名
@AfterThrowing(pointcut="myPointCut()",throwing="e")

//使用注解 配置最终增强   参数是切入点
@After(value="myPointCut()")

//使用注解 配置AfterReturning增强   参数是切入点,返回结果变量名
@AfterReturning(pointcut="myPointCut()",returning="result")

//使用注解 配置环绕增强   参数是切入点
@Around(value="myPointCut()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
logger.info("调用" + pjp.getTarget().getClass().getName() + "的" +      pjp.getSignature().getName()+"方法入参:"+Arrays.toString(pjp.getArgs()));
Object obj = null;
try {
// 让程序继续执行
// 此处的obj不接收对afterreturning没有影响
// 对程序中接受返回值有影响,所以要返回返回值
obj = pjp.proceed();
logger.debug(pjp.getTarget().getClass().getName() +"返回值是:" + obj);
return obj;
} catch (Throwable e) {
logger.error(pjp.getTarget().getClass().getName() +"方法发生异常:"+e.getMessage());
throw e;
}
finally{
logger.info(pjp.getTarget().getClass().getName() +"方法结束");
}

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