创建一个自定义注解需要两步
- 自定义注解
一. 创建自定义注解
/**
* 我自己用于测试的注解
* @author mjw
* @version 1.0.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface MyAnnotationCheck {
}
二. 创建切面
/***
* 我自己的注解切面
* @author mjw
* @version 1.0.0
*/
@Aspect
@Component
@Order(2)
@Slf4j
public class MyAnnotationAspect {
@Before("@annotation(myAnnotationCheck)")
public void doBefore(JoinPoint joinPoint, MyAnnotationCheck myAnnotationCheck) throws Throwable {
System.out.println("注解作用的方法名:"+joinPoint.getSignature().getName());
System.out.println("所在类的类名:"+joinPoint.getSignature().getDeclaringType().getSimpleName());
/**
* 获取request参数
*/
Object[] orgs = joinPoint.getArgs();
if(orgs != null && orgs.length > 0){
Class c = orgs[0].getClass();
while (null != c){
Field[] fields = c.getDeclaredFields();
for (Field f : fields){
//设置可以访问 变量名 和 变量的值
f.setAccessible(true);
System.out.println(f.getName());
System.out.println(f.get(orgs[0]));
}
// 用于结束循环
c = c.getSuperclass();
}
}
}
}
- 测试我们的注解
@Controller
@Slf4j
@RequestMapping("/job/demo")
@Api(value = "Job测试", tags = "Job测试")
public class JobDemo {
@RequestMapping(path = "/myAnnocationTest", method = {RequestMethod.POST})
@ApiOperation(value = "myAnnocationTest", notes = "myAnnocationTest")
@MyAnnotationCheck
@ResponseBody
public void myAnnocationTest(@RequestBody MyAnnotctionRequest myAnnotctionRequest){
System.out.println("外部暴露接口");
}
}
自定义注解的作用:如果我们有很多重复的代码可以把它提取并封装到注解中。降低代码耦合度
斜体样式同时我们还可以在参数上使用注解。方便我们获取。
/**
* 自定义注解请求实体
* @Author mjw
* @Version 1.0.0
**/
@Data
public class MyAnnotctionRequest {
@ApiModelProperty("名称")
@MyParamAnnotationCheck
private String name;
@ApiModelProperty("编号")
@MyParamAnnotationCheck
private String num;
@ApiModelProperty("不带注解的参数")
private String noAnnotation;
}
/***
* 我自己的注解切面
* @author mjw
* @version 1.0.0
*/
@Aspect
@Component
@Order(2)
@Slf4j
public class MyAnnotationAspect {
@Before("@annotation(myAnnotationCheck)")
public void doBefore(JoinPoint joinPoint, MyAnnotationCheck myAnnotationCheck) throws Throwable {
System.out.println("注解作用的方法名:"+joinPoint.getSignature().getName());
System.out.println("所在类的类名:"+joinPoint.getSignature().getDeclaringType().getSimpleName());
/**
* 获取request参数
*/
Object[] orgs = joinPoint.getArgs();
if(orgs != null && orgs.length > 0){
Class c = orgs[0].getClass();
while (null != c){
Field[] fields = c.getDeclaredFields();
for (Field f : fields){
MyParamAnnotationCheck paramAnnotationCheck = f.getDeclaredAnnotation(MyParamAnnotationCheckk.class);
// 只获取带注解的参数
if(paramAnnotationCheck != null){
//设置可以访问 变量名 和 变量的值
f.setAccessible(true);
System.out.println(f.getName());
System.out.println(f.get(orgs[0]));
}
}
// 用于结束循环
c = c.getSuperclass();
}
}
}
}