最近在研究缓存相关技术,突然发现通过定义Spring注解的方式来控制是否使用缓存挺好用的
使用方法
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface UsingModelCache {
boolean value() default true;
}
https://www.jianshu.com/p/bbbc9f4c7887 有一些讲解
@Documented
生成到javadoc中(javadoc 文档注释)
@Retention 注解的级别
@Retention(RetentionPolicy.SOURCE 源码 CLASS 编译码 RUNTIME 运行时(常用))
RUNTIME 主要用于运行时反射获取相关信息
@Target 限制注解的使用范围(具体怎么写点开ElementType看源码名称)
1) 类,接口,注解;
2) 属性域;
3) 方法;
4) 参数;
5) 构造函数;
6) 局部变量;
7) 注解类型;
8) 包
@Target(ElementType.METHOD)
//注解是否可以被继承
@Inherited()
注解的值是可以改变的
http://blog.csdn.net/Crabime/article/details/54880411
package com.springstudy.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//注解类型(常用runtime)
@Retention(RetentionPolicy.RUNTIME)
//注解作用范围
@Target(ElementType.METHOD)
//注解是否继承
//不太常用
@Inherited()
@interface Annotation1 {
boolean value() default true;
}
@interface Annotation2 {
//这里变量都要加()
String contest() default "";
}
package com.springstudy.annotation;
public class AnnotationClass {
@Annotation1
@Annotation2
public void A (){
}
public void B (){
}
public static void main(String[] args) {
AnnotationClass a = new AnnotationClass();
// Annotation2Class a = new Annotation2Class();
Annotation1 ant;
try {
ant = a.getClass().getMethod("A", null).getAnnotation(Annotation1.class);
System.out.println(ant.value());
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Annotation2Class extends AnnotationClass{
@Override
public void A() {
}
}