您的位置:首页 > 编程语言 > Java开发

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

2018-02-28 14:09 393 查看
本文介绍一下,用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 = "";
<
4000
span class="hljs-keyword">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;
}


在浏览器请求后,会得到下面结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐