springboot的自定义注解实现

自定义注解用法

在Spring Boot中,我们可以通过自定义注解来实现各种自定义功能,例如验证请求参数、权限控制等。下面是自定义注解的基本用法:

创建注解类

首先,我们需要创建一个注解类,通过@interface关键字来定义注解类,例如:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
    String value() default "";
}

在上面的例子中,我们定义了一个名为CustomAnnotation的注解,它有一个属性value,默认值为空字符串。注解类的注释中,使用了@Target和@Retention元注解来指定注解适用的目标和生命周期。

在需要使用注解的地方标记

然后,我们可以在需要使用这个注解的地方进行标记。例如,我们可以在某个Controller的方法上使用CustomAnnotation注解:

@RestController
public class MyController {
    
    @GetMapping("/")
    @CustomAnnotation("hello")
    public String helloWorld() {
        return "Hello World!";
    }
}

在上面的例子中,我们在helloWorld()方法上使用了@CustomAnnotation(“hello”)注解,其中的参数值为"hello"。

处理注解

最后,我们需要编写代码来处理这个注解。可以通过反射来获取注解的属性值,例如:

@Aspect
@Component
public class CustomAspect {
    
    @Around("@annotation(com.example.demo.CustomAnnotation)")
    public Object handleCustomAnnotation(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        CustomAnnotation annotation = signature.getMethod().getAnnotation(CustomAnnotation.class);
        String value = annotation.value();
        // 处理注解
        return joinPoint.proceed();
    }
}

在上面的例子中,我们使用Spring AOP框架,在handleCustomAnnotation()方法中处理CustomAnnotation注解。

通过@Around(“@annotation(com.example.demo.CustomAnnotation)”)指定切点为带有CustomAnnotation注解的方法。

然后,使用反射获取注解的属性值,即value属性的值,并进行处理。

以上是自定义注解的基本用法,可以根据需求进一步扩展和优化。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尘叶风凌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值