学习SpringMVC,顺便重温一下关于Java注解的内容
Java注解形式:
1.最基本形式:
@Entity
2.带参数:
@Entity(tableName = "vehicles")
@Entity(tableName = "vehicles", primaryKey = "id")
@InsertNew(value = "yes")
当注解只有一个元素时,可以省略value直接赋值
@InsertNew("yes")
Java注解标注范围:
类,成员,方法,参数,局部变量
自定义注解:
使用
@interface
关键字定义一个注解
定义注解中的元素,eg:
@interface MyAnnotation { String value() default "";
String name(); int age(); String[] newNames(); }
使用类型和名字,并且需要带括号,有点像接口中的方法,可以设置默认值。
You cannot use complex objects as data type.
只能支持基本数据类型(包括枚举)、基本类型数组,但是不能支持如基本数据类型的包装类,抑或是list,map等比较复杂的结构。
如上注解,可以像这样使用:
@MyAnnotation( value="123", name="Jakob", age=37, newNames={"Jenkov", "Peterson"} ) public class MyClass { }
Java内置注解:
- @Deprecated
- @Override
- @SuppressWarnings
三种注解均用来给Java编译器做说明
- @Deprecated 表示过期,用于类,方法和成员
- @Override 表示覆盖父类方法,用于方法级别(在重写父类方法时,override并不是必须使用的,但是仍然建议使用它,
因为当诸如父类方法名有变动等情况时,@Override接口可以及时发现并提示错误) - @SuppressWarnings 用于告诉编译器压制警告,用于方法级别
java.lang.annotation包下的注解:
@Retention
这个注解用来修饰注解的保留级别,含有一个参数
RetentionPolicy value();
RetentionPolicy是一个枚举类型,含有三个选择:SOURCE,CLASS,RUNTIME
@SuppressWarnings
@Override
CLASS代表注解会被编译到.class文件当中作为保留。
RUNTIME代表注解的内容会被JVM获取,如
@Deprecated
默认形式为CLASS形式。
@Target
这个注解用来修饰注解的作用对象,含有一个数组参数
ElementType[] value();
ElementType是一个枚举类型,有如下几个选择:
- ElementType.ANNOTATION_TYPE 仅能修饰其他注解,如@Retention,@Target等;
- ElementType.CONSTRUCTOR
- ElementType.FIELD
- ElementType.LOCAL_VARIABLE
- ElementType.METHOD
- ElementType.PACKAGE
- ElementType.PARAMETER
- ElementType.TYPE 能够修饰class,interface,enum,annotation;
@Inherited
表示该注解能够在class的继承关系中传递。
@Documented
使该注解的信息能够在JavaDoc中显示。
http://tutorials.jenkov.com/java/annotations.html#override