zoukankan      html  css  js  c++  java
  • Java自定义注解的实现

    Java自定义注解的实现,总共三步(eg.@RandomlyThrowsException):

    1.首先编写一个自定义注解@RandomlyThrowsException

    package com.github.prontera;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    public @interface RandomlyThrowsException {
    }
    

    2.编写自定义注解@RandomlyThrowsException的实现

    package com.github.prontera.aspect;
    
    import com.github.prontera.config.ManualExceptionProperties;
    import com.github.prontera.exception.ManualException;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.springframework.core.Ordered;
    
    import java.security.SecureRandom;
    import java.util.Random;
    
    @Aspect
    public class ManualExceptionAspect implements Ordered {
        private final int order;
        private final ManualExceptionProperties properties;
        private static final Random RANDOM = new SecureRandom();
    
        public ManualExceptionAspect(int order, ManualExceptionProperties properties) {
            this.order = order;
            this.properties = properties;
        }
    
        @Around("@annotation(com.github.prontera.RandomlyThrowsException)")
        public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
            if (properties.isEnabled()) {
                if (RANDOM.nextInt(100) % properties.getFactor() == 0) {
                    throw new ManualException("manual exception");
                }
            }
            return joinPoint.proceed();
        }
    
        @Override
        public int getOrder() {
            return order;
        }
    }
    

    3.使用自定义注解@RandomlyThrowsException

        @Delay
        @RandomlyThrowsException
        @ApiOperation(value = "下单", notes = "生成预订单")
        @RequestMapping(value = "/orders", method = RequestMethod.POST)
        public ObjectDataResponse<Order> placeOrder(@Valid @RequestBody PlaceOrderRequest request, BindingResult result) {
            return orderService.placeOrder(request);
        }
    

      

  • 相关阅读:
    BZOJ 1911: [Apio2010]特别行动队
    BZOJ 1096: [ZJOI2007]仓库建设(动态规划+斜率优化)
    BZOJ 2243: [SDOI2011]染色(树链剖分)
    BZOJ 1834: [ZJOI2010]network 网络扩容(网络流+费用流)
    BZOJ 1036: [ZJOI2008]树的统计Count(树链剖分)
    BZOJ 1875: [SDOI2009]HH去散步(矩阵乘法)
    BZOJ 1898: [Zjoi2004]Swamp 沼泽鳄鱼(矩阵乘法)
    BZOJ 2463: [中山市选2009]谁能赢呢?(博弈论)
    BZOJ 2879: [Noi2012]美食节
    BZOJ 1070: [SCOI2007]修车(费用流)
  • 原文地址:https://www.cnblogs.com/therunningfish/p/8538849.html
Copyright © 2011-2022 走看看