Spring注解与Java元注解小结

注解 Annotation

基于注解的开发,使得代码简洁,可读性高,简化的配置的同时也提高了开发的效率,尤其是 SpringBoot 的兴起,随着起步依赖和自动配置的完善,更是将基于注解的开发推到了新的高度。

元注解 meta-annotation

Java 5 定义了四个标准的元注解类型,用以提供对其它注解的功能说明。

位于 java.lang.annotation 包下,分别为:

  1. @Target

  2. @Retention

  3. @Documented

  4. @Inherited

以 @Profile 注解为例:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ProfileCondition.class)
public @interface Profile {
</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * The set of profiles for which the annotated component should be registered.
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
String[] value();

}

@Target

说明注解所修饰的对象范围。

注解可用于:package、type(类、接口、枚举、注解)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(循环变量、catch 参数)。

按照作用范围,个人给出的常用注解,按照作用范围排序,各类暂举一:

  @Configuration、@MapperScan、@RestController、@RequestMapping、@ResponseBody、@Autowired、@Resource、@Value、@PathVariable。。。

具体的取值范围为 ElementType(enum)类型的数组,见源码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}
  1. ElementType.Constructor : 描述构造器
  2. ElementType.Field : 描述域
  3. ElementType.LocalVariable : 描述局部变量
  4. ElementType.Method : 描述方法
  5. ElementType.Package : 描述包
  6. ElementType.Parameter : 描述参数
  7. ElementType.Type : 描述类、接口、enum、annotation

@Retention

定义注解的作用时期(源文件、字节码、运行期)。

用以 说明被描述的注解在什么范围内生效。

取值唯一,即具体的保存策略,RetentionPolicy(enum)之一。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();}

RetentionPolicy 包括:

  1. SOURCE : 源文件有效
  2. CLASS : 字节码文件有效
  3. RUNTIME : 运行时有效

@Documented

标记注解,可被 javadoc 之类的工具文档化,即描述该类型的注解,应该作为被标注的程序成员的公共 API,没有成员

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}

@Inherited

标记注解,描述的注解是可被继承的。即如果一个类被 @Inherited 标记的注解所修饰,则该注解同样作用于这个类的子类。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}