1刃泡、在pom文件中添加aop的依賴
2巧娱、使用示例參考如下
/**
*@authorfangzy
*@since2017/8/14.
*類級(jí)注解:
*@Aspect聲明這是一個(gè)切面對(duì)象
*方法級(jí)注解:
*@Pointcut聲明一個(gè)切點(diǎn)規(guī)則
*@Before方法執(zhí)行之前,執(zhí)行通知烘贴。
*@After方法執(zhí)行之后禁添,不考慮其結(jié)果,執(zhí)行通知桨踪。
*@AfterReturning方法執(zhí)行之后老翘,只有在方法成功完成時(shí),才能執(zhí)行通知
*@AfterThrowing方法執(zhí)行之后,只有在方法退出拋出異常時(shí)铺峭,才能執(zhí)行通知
*@Around在方法調(diào)用之前和之后墓怀,執(zhí)行通知 等價(jià)于上面四個(gè)相加
*/
@Component
@Aspect
public classMyAdvice {
Loggerlogger= LoggerFactory.getLogger(MyAdvice.class);
// expression配置切點(diǎn)的表達(dá)式,切到哪
@Pointcut("execution(* com.example.springboot.*Service.*(..))")
private voidbusinessService() {
}
//在一個(gè)方法執(zhí)行之前卫键,執(zhí)行通知傀履。
@Before("businessService()")
public voiddoBeforeTask(JoinPoint joinPoint) {
logger.info("doBeforeTask.");
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
logger.info("請(qǐng)求的ip:{}",request.getRemoteAddr());
logger.info("請(qǐng)求的uri:{}",request.getRequestURI());
logger.info("請(qǐng)求的method:{}",request.getMethod());
logger.info("請(qǐng)求的類方法:{}.{}",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName());
logger.info("請(qǐng)求參數(shù){}",joinPoint.getArgs());
}
//在一個(gè)方法執(zhí)行之后,不考慮其結(jié)果莉炉,執(zhí)行通知钓账。
@After("businessService()")
public voiddoAfterTask() {
logger.info("doAfterTask.");
}
//在一個(gè)方法執(zhí)行之后,只有在方法成功完成時(shí)絮宁,才能執(zhí)行通知梆暮。
@AfterReturning(pointcut="businessService()",returning="retVal")
public voiddoAfterReturnningTask(JoinPoint joinPoint,Object retVal) {
String methodName = joinPoint.getSignature().getName();
logger.info("doAfterReturnningTask {} return with {}",methodName,retVal);
}
//在一個(gè)方法執(zhí)行之后,只有在方法退出拋出異常時(shí)绍昂,才能執(zhí)行通知
@AfterThrowing(pointcut="businessService()",throwing="ex")
public voiddoAfterThrowingTask(JoinPoint joinPoint,Exception ex) {
String methodName = joinPoint.getSignature().getName();
logger.info("doAfterThrowingTask {} occurs exception: {} ",methodName,ex);
}
//在建議方法調(diào)用之前和之后惕蹄,執(zhí)行通知。
@Around("businessService()")
publicObjectdoAroundTask(ProceedingJoinPoint jpoint) {
Object result =null;
String methodName = jpoint.getSignature().getName();
//執(zhí)行目標(biāo)方法
try{
//前置通知
logger.info("The method {} begins with {}",methodName,Arrays.asList(jpoint.getArgs()));
result = jpoint.proceed();
//返回通知
logger.info("The method {} ends with {} ",methodName,Arrays.asList(jpoint.getArgs()));
}catch(Throwable e) {
//異常通知
logger.info("The method {} occurs expection {} ",methodName,e);
throw newRuntimeException(e);
}
//后置通知
logger.info("The method {} ends",methodName);
returnresult;
}
}