返回信息枚举 TipsMsg:
public enum TipsMsg {
DEFAULT_SUCCESS("0","操作成功"),
DEFAULT_FAILED("1","操作失败"),
//其他枚举
//get
//set
}
自定义注解 ReturnMsg (也是切点) :
@Target(ElementType.METHOD)//方法上声明
@Retention(RetentionPolicy.RUNTIME)//注解将被编译器记录在class文件中,而且在运行时会被虚拟机保留,因此它们能通过反射被读取到
public @interface ReturnMsg {
TipsMsg successMsg() default TipsMsg.DEFAULT_SUCCESS;
TipsMsg failedMsg() default TipsMsg.DEFAULT_FAILED;
}
AOP切面:
@Aspect//声明切面
@Component
public class ReturnMsgAspect {
private Logger logger = LoggerFactory.getLogger(ReturnMsgAspect.class);
@Pointcut("@annotation(xx.xxx.xx.xx.xx.xx.xx.ReturnMsg)")//切点为注解全路径
public void ReturnMsgPointcut(){
}
@Around(value = "ReturnMsgPointcut()")
public Object serviceAround(ProceedingJoinPoint joinPoint) throws Throwable {
//返回值统一
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//获取返回值类型
Class returnType = signature.getReturnType();
//获取注解
ReturnMsg returnMsg = signature.getMethod().getAnnotation(ReturnMsg.class);
String msg = returnMsg.successMsg().getTipsMsg();
String code = returnMsg.successMsg().getCode();
Object returnObj = null;
try {
returnObj = joinPoint.proceed();
} catch (Exception e) {
e.printStackTrace();
throw new ZTBusinessException(BaseRspConstants.RSP_CODE_FAILD, returnMsg.failedMsg().getTipsMsg());
}
RspBaseBO rspBaseBO = BizEntityApis.buildRspBaseBO(code, msg);
if(returnObj instanceof RspBaseBO){//调用成功时,有返回值且为RspBaseBO子类
((RspBaseBO) returnObj).setMessage(msg);//默认成功返回值set进去
returnObj = returnType.cast(returnObj);
}
return returnObj;
}
}
使用
@ReturnMsg(successMsg = TipsMsg.DEFAULT_SUCCESS,failedMsg = TipsMsg.DEFAULT_FAILED)
public RspBaseBO serviceA (Input in) {
//业务方法,joinPoint.proceed()所调用的方法
}
execution表表达式也可作为切点,mark下