@Documented 的作用

1. @Documented 的含义

  • @Document 是 java 在生成文档,是否显示注解的开关。

2. 加和不加有什么区别?

  • 测试注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RestMapping {
  String[] value() default {};

  String[] path() default {};
}
  • 测试类 TerminalController
@RestMapping("/terminal")
public class TerminalController {

  • 使用命令
// 生成 java doc 的命令:
javadoc -d doc TerminalController.java`
// -d <directory>  输出文件的目标目录

a. 不加的效果

在这里插入图片描述

b. 加上的效果

在这里插入图片描述

可以看到在 public class TerminalController 上面多了一个我们写的注解。这就是 @Documented 的用处。

3. 题外话:注解合并

java 注解原本只是一种不会被编译器忽略的注释。本身对代码逻辑没有任何影响(可以用来判断是否存在,能读取内容信息),而使用效果完全由使用工具决定。

注解被很多规范使用,作为标记或者约定,如 jsr303 参数校验。

a. 注解合并

在 springboot 中注解发挥了很大的作用,而这些作用仅在springboot中有用,就好比@AliasFor。

注解本身并不能被注解继承,而 springboot 中却看到大量的合并注解就好比 @RestController = @Controller + @ResponseBody。这就是 @AliasFor 的功劳。需要注意的是,离开 Spring 就无法使用了。

spring 的注解都是由下面这个类读取的,所以 spring 的注解可以进行注解合并(有且仅限 spring 注解:Spring Annotations)

public interface MergedAnnotations

b. @AliasFor

@AliasFor 有四个作用:

  1. 注释中的显式别名:
    在@ContextConfiguration中, value和locations是彼此的显式别名。
public @interface ContextConfiguration {
  @AliasFor("locations")
  String[] value() default {};
  
  @AliasFor("value")
  String[] locations() default {};
  
  // ...
}
  1. 元注释中属性的显式别名:
    在@XmlTestConfig中, xmlFiles是@ContextConfiguration中locations的显式别名。换句话说, xmlFiles覆盖了@ContextConfiguration中的locations属性。
 @ContextConfiguration
   public @interface XmlTestConfig {
  
      @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
      String[] xmlFiles();
   }
  1. 注释中的隐式别名:
    在@MyTestConfig中, value 、 groovyScripts和xmlFiles都是@ContextConfiguration中locations属性的显式元注释属性覆盖。因此,这三个属性也是彼此的隐式别名。
 @ContextConfiguration
public @interface MyTestConfig {
  @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
  String[] value() default {};
  
  @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
  String[] groovyScripts() default {};
  
  @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
  String[] xmlFiles() default {};
}
  1. 注释中的传递隐式别名:
    在@GroovyOrXmlTestConfig中, groovy是对@MyTestConfig中groovyScripts属性的显式覆盖;而xml是对@ContextConfiguration中的locations属性的显式覆盖。此外, groovy和xml是彼此的可传递隐式别名,因为它们都有效地覆盖了@ContextConfiguration中的locations属性。
@MyTestConfig
public @interface GroovyOrXmlTestConfig {
  @AliasFor(annotation = MyTestConfig.class, attribute = "groovyScripts")
  String[] groovy() default {};
  
  @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
  String[] xml() default {};
}

(完)

  • 14
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值