我们可以使用springboot自定义注解来创建自己的注解,下面就详解3步来创建springboot自定义注解@mikechen
1.创建SpringBoot自定义注解类
创建一个新的Java类,用于定义自定义注解。
如下所示:
package com.example.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) // 定义注解的适用范围为方法 @Retention(RetentionPolicy.RUNTIME) // 定义注解在运行时可见 public @interface CustomAnnotation { // 在注解中定义属性 String value() default ""; // 可以定义多个属性 }
在注解类中,使用 @Target
注解来指定注解适用的目标元素,比如:方法、类、字段等。
使用 @Retention
注解来指定注解的生命周期,如保留到运行时。
2.创建一个包含SpringBoot自定义注解的类
并在其中使用自定义注解,如下所示:
package com.example.services; import com.example.annotations.CustomAnnotation; public class MyService { @CustomAnnotation(value = "customValue") // 使用自定义注解,并指定属性值 public void doSomething() { // 执行具体的操作 System.out.println("Doing something..."); } }
在代码中使用自定义注解时,通过 @注解名称 的方式使用,并可以为属性赋予具体的值。
3.使用SpringBoot自定义注解类
使用反射机制读取注解信息,如下所示:
package com.example; import com.example.annotations.CustomAnnotation; import com.example.services.MyService; import java.lang.reflect.Method; public class Main { public static void main(String[] args) throws NoSuchMethodException { MyService myService = new MyService(); // 获取 MyService 类中的 doSomething 方法 Method method = MyService.class.getMethod("doSomething"); // 检查方法上是否存在 CustomAnnotation 注解 if (method.isAnnotationPresent(CustomAnnotation.class)) { CustomAnnotation annotation = method.getAnnotation(CustomAnnotation.class); String value = annotation.value(); System.out.println("CustomAnnotation value: " + value); } // 调用 doSomething 方法 myService.doSomething(); } }
运行 Main 类,输出结果为
CustomAnnotation value: customValue Doing something...
在这个示例中,我们定义了一个 SpringBoot自定义注解:CustomAnnotation ,并将其应用于 doSomething 方法,并进行相应的处理。
以上就是springboot自定义注解详解,更多内容请查看:SpringBoot教程(万字图文详解)
mikechen
mikechen睿哥,10年+大厂架构经验,资深技术专家,就职于阿里巴巴、淘宝、百度等一线互联网大厂。
关注「mikechen」公众号,获知最新一线技术干货!
