用Spring Aop方式拦截自定义注解的实现

本文介绍一下,用aop的方式实现对自定义注解的使用,所用框架是SpringBoot

引入maven依赖

 <!-- 引入aop支持 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

自定义注解

注释写的很清楚

/*** 
 * @ClassName MyTag.java
 * <p>Description: </p>
 * @author 沉鱼
 * @date 2018年2月28日 下午2:02:44
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyTag {
    int age() default 0;
}

配置Aop

@Component
@Aspect
public class MyTagAop {

    @Before(value="@annotation(com.zycz.myproject.annotation.MyTag)")
    public void dofore(JoinPoint jp) {
        try {
            //通过获取MyTag注解
            Method proxyMethod = ((MethodSignature) jp.getSignature()).getMethod();
            Method targetMethod = jp.getTarget().getClass().getMethod(proxyMethod.getName(), proxyMethod.getParameterTypes());
            MyTag myTag = targetMethod.getAnnotation(MyTag.class);
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            //处理注解逻辑
            int age = myTag.age();
            String tip = "";
            if (age <= 30 && age > 0) {
                tip = "年纪小于30岁先做程序员吧";
            }else if (age > 30 && age < 35) {
                tip = "年纪在30至35之间可以回去考公务员了";
            }else {
                tip = "你的年纪不在我考虑范围之内";
            }
            request.setAttribute("tip", tip);
        } catch (Throwable e) {
            System.out.println("有异常啊");
        }
    }
}

校验

简单写了下

@GetMapping(value="/testsMyTag")
@MyTag(age=26)
public String testMyTag(HttpServletRequest request,HttpServletResponse response){
        String tip = (String) request.getAttribute("tip");
        return tip;
}

在浏览器请求后,会得到下面结果
这里写图片描述

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值