Spring自定义注解

[b]Spring自定义注解[/b]


[b]@Target(ElementType.METHOD)[/b]
用来说明该注解可以被声明在那些元素之前。
ElementType.TYPE:说明该注解只能被声明在一个类前。
ElementType.FIELD:说明该注解只能被声明在一个类的字段前。
ElementType.METHOD:说明该注解只能被声明在一个类的方法前。
ElementType.PARAMETER:说明该注解只能被声明在一个方法参数前。
ElementType.CONSTRUCTOR:说明该注解只能声明在一个类的构造方法前。
ElementType.LOCAL_VARIABLE:说明该注解只能声明在一个局部变量前。
ElementType.ANNOTATION_TYPE:说明该注解只能声明在一个注解类型前。
ElementType.PACKAGE:说明该注解只能声明在一个包名前。


[b]@Retention(RetentionPolicy.RUNTIME)[/b]
RetentionPolicy.SOURCE : 注解只保留在源文件中
RetentionPolicy.CLASS : 注解保留在class文件中,在加载到JVM虚拟机时丢弃
RetentionPolicy.RUNTIME : 注解保留在程序运行期间,此时可以通过反射获得定义在某个类上的所有注解。


[b]@Inherited[/b]
1.允许子类继承父类的注解。
2.注意:在这种情况下,并不是应用在所有的地方,只有父类在在"类"这个级别上使用的annotation才能被继承,
如果声明在方法、变量等地方的annotation不会被继承


[b]@Documented[/b](可以不管)


[b]例子:[/b]
Description.java
@Target(ElementType.METHOD )
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented

public @interface Description {
String desc();
String author();
int age() default 18;
}


Person.java
public class Person {
@Description(desc="yong",author="xing",age=19)
public void sayHello(){
System.out.println("Hello");
}

@Description(desc="yong",author="xing",age=19)
public void sayHello2(){
System.out.println("Hello2");
}

public static void main(String[] args) {
Person person = new Person();
person.sayHello();
Method[] m = Person.class.getDeclaredMethods(); //得到一个类的所有方法

System.out.println("len = " + m.length);

for (Method m2 : m) {
Description description = m2.getAnnotation(Description.class);//得到方法上的注解
System.out.println("description = " + description);
if (description != null) {
System.out.println("description:" + description.desc() + " "
+ description.author() + " "+ description.age() + " "); 得到注解上的内容
}
}
}
}



参考原文:[url]http://www.tuicool.com/articles/2MRZJn[/url]
参考原文:[url]http://xiangdefei.iteye.com/blog/1044199[/url]
参考原文:[url]http://blog.csdn.net/maguanghui_2012/article/details/69372209[/url]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值