Target:描述了注解修饰的对象范围,取值在java.lang.annotation.ElementType定义,
- METHOD:用于描述方法
- PACKAGE:用于描述包
- PARAMETER:用于描述方法变量
- TYPE:用于描述类、接口或enum类型
Retention: 表示注解保留时间长短。取值在java.lang.annotation.RetentionPolicy中,取值为:
- SOURCE:在源文件中有效,编译过程中会被忽略
- CLASS:随源文件一起编译在class文件中,运行时忽略
- RUNTIME:在运行时有效
只有定义为RetentionPolicy.RUNTIME时,我们才能通过注解反射获取到注解。
2 重试注解(1)定义重试注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RetryAnnotation {
int retryTimes() default 0 ;
MidBackoff backoff() default @MidBackoff();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@documented
public @interface MidBackoff {
int count() default 10;
double multiplier() default 0;
int delay() default 0;
}
(2)重试切面
@RefreshScope
@Component
@Aspect
@Slf4j
public abstract class RetryAspect {
// 切入点
@Pointcut("@annotation(com.sr.bizmid.tradeCore.common.annotation.RetryAnnotation)")
public void pointCut() {
}
// joinPoint 连接点
@Around("pointCut()")
public Object process(ProceedingJoinPoint joinPoint, RetryAnnotation retryAnnotation) throws Throwable {
AtomicReference
(3)RPC 调用使用重试注解
@RetryAnnotation(backoff = @MidBackoff(count = 5,multiplier = 1,delay = 30))
public void writeOFFCoupon(OperateCouponsRequest operateCouponsRequest){
HttpResult httpResult;
try {
log.info("调用核销优惠券请求入参:{}", JSON.toJSonString(operateCouponsRequest));
httpResult = couponClient.operateCoupons(operateCouponsRequest);
log.info("调用核销优惠券请求response:{}", JSON.toJSonString(httpResult));
}catch (Exception e) {
throw new TRetailRpcResultException(TradeRpcErrorCode.TRADE_CALL_COUPON_ERROR, e);
}
if (!httpResult.isSuccess() || httpResult.getData() == null) {
throw new TRetailRpcResultException(TradeRpcErrorCode.TRADE_CALL_COUPON_ERROR);
}
}
3 商品校验注解
(1)定义注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SettleCheck {}
(2)校验切面
public class ValidatorAspect{
@Pointcut("@annotation(com.sr.bizmid.tradeCore.common.annotation.SettleCheck)")
public void pointCut() {
}
@Around("pointCut()")
public void process(ProceedingJoinPoint joinPoint) throws Throwable {
Signature signature = joinPoint.getSignature();
Class targetClass = signature.getDeclaringType();
if (checkHavingValidGoods() || checkWhetherLimitCheck()) {
log.warn("存在无效商品: 组件类名为:{}", targetClass.getSimpleName());
return;
}
joinPoint.proceed();
}
}
(3)商品操作前,基于注解执行校验逻辑
@Component
public class CommodityPrescriptionBuilder {
@SettleCheck
public void buildDomain() {
// 商品操作逻辑
}
}



