spring-AOP


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
* @author
*/
@Slf4j
@Aspect
@Component
public class SaveMessageAspect {}


@Autowired
private KafkaTemplate<String, Object> kafkaTemplate;

@Autowired
protected PictureToOssClient pictureToOssClient;

@Autowired
private ThreadPoolConfig threadPoolConfig;

/**
* 前置通知
* pointcut()指定的是切入点注解所标注的方法名
* @Before注解的value属性指定的是切入点注解所标注的方法名,
* 结果不同通知想使用不同的切入点
*/


@Pointcut("execution(public * com.midea.ocr.api.controller.BizLicenseRecController.*(..))")
public void saveMessage(){};


@Before("saveMessage()")
public void before(JoinPoint joinPoint){
System.out.println("切面before方法开始------------------------------------");


}




/**
* 环绕通知
* @param pjp 连接点,可以获取目标方法参数以及方法信息以及调用目标方法等等
*/
@Around("saveMessage()")
public Object around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("环绕通知前。。。");

}

/**
* 后置通知 ResponseVO
* @param
*/
@AfterReturning(value = "saveMessage()", returning = "responseVo")
public void afterReturning(JoinPoint joinPoint, ResponseVO responseVo){

String methodName = joinPoint.getSignature().getName();

System.out.println("方法"+methodName+"方法返回,返回值为:"+JSONObject.toJSONString(responseVo));


}

/**
* 异常通知
* @param ex 目标方法产生的异常对象
*/
@AfterThrowing(throwing = "ex", pointcut = "saveMessage()")
public void afterThrowing(JoinPoint joinPoint,Throwable ex){

String methodName = joinPoint.getSignature().getName();

System.out.println(methodName+"方法异常,异常信息为:"+ex.getMessage());
log.error(methodName+"方法异常,异常信息为:",ex.getMessage());

}

/**
* 最终通知
*/
@After("saveMessage()")
public void after(){
System.out.println("最终通知");
}


}

 

 @AfterReturning注解标注的方法需注意:入参一定与执行切面方法的返参类型一致(之前名称一致但包路径不同浪费了很长时间排查)

 @Before   注解标注的方法需注意: 根据

joinPoint.getArgs()获取的 object[]  参数顺序与执行切面方法的入参顺序一致.

 

posted @ 2021-12-21 09:38  悄悄地超越  阅读(20)  评论(0编辑  收藏  举报