zoukankan      html  css  js  c++  java
  • 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 {
    
        /**
         * The set of profiles for which the annotated component should be registered.
         */
        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 {
    }
  • 相关阅读:
    USACO / Longest Prefix最长前缀(DP)
    (转)HDOJ 4006 The kth great number(优先队列)
    STL priority_queue(优先队列(堆))
    康托展开
    USACO / Magic Squares(经典BFS+Cantor展开hash)
    国家集训队论文分类整理
    国家集训队论文分类整理
    国家集训队论文分类整理
    OI / ACM 知识归纳
    学年总结跋涉ACM之路
  • 原文地址:https://www.cnblogs.com/nyatom/p/9146451.html
Copyright © 2011-2022 走看看