Java注解

作用

给代码贴的标签/标记,本身不做任何事,只是携带信息,由解析器(反射 / AOP / 框架)读取并执行逻辑

自定义注解

使用@interface表示是一个注解

元注解

作用是注解在别的注解上的注解

  • @Target:描述解可以用在什么地方
  • @Retention:描述注解保留到什么时候
    • SOURCE:只在源码阶段保留
    • CLASS:保留到编译器
    • RUNTIME:保留到运行期(默认)
  • @Documented:在使用 javadoc 工具为类生成帮助文档时是否要保留其注解信息
  • @Inherited:使注解具有继承性

示例

  1. 定义一个注解

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package com.xw.annotation;

    import java.lang.annotation.*;

    // 元注解:规定注解能写在哪些地方
    @Target({ElementType.METHOD, ElementType.TYPE})
    // 元注解:规定注解保留到什么时候
    @Retention(RetentionPolicy.RUNTIME)
    // 生成文档
    @Documented
    public @interface MyLog {

    // 定义属性:写法 类型 + 属性名()
    String value() default "";

    boolean enable() default true;

    }
  2. 定义AOP

    注解本身不会自动执行,必须通过 反射 / AOP 读取并处理。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    package com.xw.aop;

    @Aspect
    @Component
    @Order
    public class MyLogAspect {

    // 切点:所有贴了 @MyLog 的方法
    @Pointcut("@annotation(com.xw.annotation.MyLog)")
    public void pointcut() {}

    // 环绕通知
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    // 1. 获取方法上的注解
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    MyLog myLog = signature.getMethod().getAnnotation(MyLog.class);

    // 2. 获取注解里的值
    String value = myLog.value();
    boolean enable = myLog.enable();

    // 3. 写你的业务逻辑(日志、权限、校验...)
    System.out.println("注解value:" + value);
    System.out.println("注解enable:" + enable);

    // 4. 执行目标方法
    return joinPoint.proceed();
    }
    }
  3. 使用注解

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    package com.xw.controller;

    @RestController
    public class TestController {

    // 贴上自定义注解
    @MyLog(value = "测试接口", enable = true)
    @GetMapping("/test")
    public String test() {
    return "ok";
    }
    }

Java注解
http://xwww12.github.io/2026/06/02/编程语言/java/Java注解/
作者
xw
发布于
2026年6月2日
许可协议