**
需求:定义一个注解,用于比较注解中某个参数值是否和修饰的方法的参数值相等。
**
步骤:
1. 定义一个注解名为ValidQuery
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ValidQuery {
String name();
}
说明:
a)@Target(ElementType.METHOD):
注解能够使用的地方,此处为方法上。一般使用的地方可以有:类(CLASS)、全局变量(FIELD)、方法(METHOD)、局部变量(LOCAL_VARIABLE)等。
b)@Retention(RetentionPolicy.RUNTIME):
保留策略。一般有三种:SOURCE:保留到源文件中,当JVM编译为字节码文件后就不存在了。CLASS:保存在.class文件中,但是系统运行时就不存在了。
RUNTIME:运行时保留,这也是用的最多的时候。
c)@Inherited:
表示该注解可被继承。当一个类上标注了该注解,该类被另一个类继承,如果该子类没有被其他注解标注,则该注解会被标注到子类上。
d)注解内部定义一些注解中的属性。和类中属性不同,这里所有属性后要加“()”。
2. 定义切面类
@org.aspectj.lang.annotation.Aspect
@Component
public class Aspect {
@Pointcut("@annotation(com.huang.ValidQuery)")
public void annotationCut() {}
@Before("annotationCut()")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
Method method = signature.getMethod();
ValidQuery annotation = method.getAnnotation(ValidQuery.class);
String name = annotation.name();
Object[] args = joinPoint.getArgs();
int a = 0;
for (Object arg : args) {
if (name.equals(arg)) {
a = 1;
break;
}
}
if (a == 1) {
System.out.println("方法中的参数和注解中的参数一样!!");
} else {
System.out.println("不一样!!!");
}
}
}
说明:切面类中要有切点和Before或After或Around方法
测试
@RestController
public class Controller {
@RequestMapping(value = "/annotation", method = RequestMethod.GET)
@ValidQuery(name = "test")
public String controller(@RequestParam("name") String name){
return "注解测试";
}
}
总结:
实际上注解没有多高级。他只是会和修饰的方法等发生一定的联系,根据我们的需求写相应的逻辑代码即可!