java 与spring 注解_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 @interfaceProfile {/*** 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 @interfaceTarget {/*** Returns an array of the kinds of elements an annotation type

* can be applied to.

*@returnan array of the kinds of elements an annotation type

* can be applied to*/ElementType[] value();

}

ElementType.Constructor : 描述构造器

ElementType.Field : 描述域

ElementType.LocalVariable : 描述局部变量

ElementType.Method : 描述方法

ElementType.Package : 描述包

ElementType.Parameter : 描述参数

ElementType.Type : 描述类、接口、enum、annotation

@Retention

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

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

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

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.ANNOTATION_TYPE)public @interfaceRetention {/*** Returns the retention policy.

*@returnthe retention policy*/RetentionPolicy value();

}

RetentionPolicy包括:

SOURCE : 源文件有效

CLASS : 字节码文件有效

RUNTIME : 运行时有效

@Documented

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

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.ANNOTATION_TYPE)public @interfaceDocumented {

}

@Inherited

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

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.ANNOTATION_TYPE)public @interfaceInherited {

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值