qq_29917909 2021-05-25 15:42 采纳率: 100%
浏览 730
已采纳

springboot 自定义注解和切面不生效

controller

@RestController
@RequestMapping("app/111")
public class test {

    /**
     * 登录界面开关
     * @return
     */
    @PostMapping("/loginOnOff1")
    @CheckForm(delaySeconds = 1,checkType = "sd")
    private ApiResult loginOnOff1() {
        System.out.println("测试");
        return null;

    }
}

注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckForm {

    int delaySeconds() default 5;

    String checkType() default "";
}

切面

@Aspect
@Component
@Slf4j
public class SubmitAspect {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CommonCacheUtil cacheUtil;


    @Pointcut(value = "@annotation(com.fengou.common.annotation.CheckForm)")
    private void pointcut() {
        System.out.println("111111");
    }


    @Around("pointcut()&&@annotation(checkForm)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint,CheckForm checkForm ) throws Throwable {

        Integer delaySeconds = checkForm.delaySeconds();

        String checkType = checkForm.checkType();
        UserElement ue;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = request.getHeader(Constants.REQUEST_TOKEN_KEY);

        Boolean falg = redisTemplate.opsForValue().setIfAbsent(token+":"+checkType,1,delaySeconds, TimeUnit.SECONDS);
      //  boolean falg = true;
        if (falg){
            log.error("正确执行了");
            return proceedingJoinPoint.proceed();

        }else {
            log.error("错误执行了");
            return ApiResult.createByInfo(ResponseCode.SUBMIT_ERROR.getCode());
        }



    }
}
  • 写回答

2条回答 默认 最新

  • CSDN专家-毛惜时 2021-05-25 17:49
    关注

    aop的原理是动态代理,被拦截的方法不能是private,将方法loginOnOff1的private改为public就可以被拦截了。修改后的代码如下:

    @RestController
    @RequestMapping("app/111")
    public class test {
    
        /**
    
         * 登录界面开关
    
         * @return
    
         */
        @PostMapping("/loginOnOff1")
        @CheckForm(delaySeconds = 1,checkType = "sd")
        public ApiResult loginOnOff1() {
            System.out.println("测试");
            return null;
        }
    
    }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于ucc28019的pfc电路中芯片一直不工作
  • ¥15 yolov8在3588板子端c++推理报错
  • ¥50 unitywebrequest分段下载导致报错,如何解决?
  • ¥15 错误使用 gretna_GUI_PreprocessInterface>RunBtn_Callback
  • ¥15 WPF如何用Chart绘画出Y轴的左边数据
  • ¥15 pycharm无法查看内置代码
  • ¥15 跑hls xfopencv的例程standalone_hls_axi_example出的错误,csim没问题,c synthesis出的错误
  • ¥15 sqlserver update语句逐行生效
  • ¥20 Windows10系统命令行调用
  • ¥15 php环境如何实现国密SM2相关功能