开篇明义
注解是一种元数据,把元数据跟源码结合起来,方便我们在需要的时刻获得这些元数据的值,并且根据这些元数据做相应的处理;
如果你不能理解,我给你打个比方:注解相当于给源码打个标签,比如我把某个方法打上了苹果的标签,那么在某一个需要的时候,我就可以根据某种方式拿到打上苹果标签的方法,对它进行我们的逻辑处理;
元注解:用于注解其他的注解,也就是注解的注解;
元注解的数量很少
@Target, //用来表明该注解可以用于什么地方,可以是对应的类,方法,字段,包等
@Retention,//表示需要在什么级别保存该注解的信息,SOURCE,CLASS,RUNTIME
@Documented, //将此注解包含在javadoc中
@Inherited, //允许子类继承父类中的注解
如何编写注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//可以用在类上和方法上
@Target({ElementType.METHOD,ElementType.TYPE})
//运行时
@Retention(RetentionPolicy.RUNTIME)
public @interface test{
//对应的值,也可以加默认值
String value();
}
如何使用注解
@test("w")
public List<Student> mysqlTest1(){
return testMapper.listStudent();
}
如果找到对应的注解?
有一个接口叫AnnotatedElement
![](https://img-blog.csdnimg.cn/img_convert/cafe4347c2a9b70144a3a84e1f5ab8e6.webp?x-oss-process=image/format,png)
image.png
![](https://img-blog.csdnimg.cn/img_convert/0dc8498dfb80b69b4707a26c63ea1d27.webp?x-oss-process=image/format,png)
image.png
![](https://img-blog.csdnimg.cn/img_convert/9672bded3511fd6a1f5f6b9a92e66f2e.webp?x-oss-process=image/format,png)
image.png
我们可以看到Method,Field,Class这三个类都继承了AnnotatedElement;
AnnotatedElement有可以操作注解的方法,比如 <T extends Annotation> T getAnnotation(Class<T> annotationClass)
具体情况 https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/AnnotatedElement.html
通过getAnnotation可以得到对应的注解,通过注解可以直接得到属性;
如何灵活应用:
1:直接使用;
2:通过拦截器配合使用;
3:使用AOP配合使用;
4:使用BeanPostProcessor配合使用;
目前我用过的有这四种;具体例子不举了;