Spring注解的使用

最近在研究缓存相关技术,突然发现通过定义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() {
		
	}
	
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值