自定义注解

1、定义注解;

import java.lang.annotation.*;

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

2、使用注解;

在对应的实体上方的字段进行应用注解;

3、使用反射机制查看注解的属性;

import com.annotiondemo.annotion.Cacheable;
import com.annotiondemo.domain.Person;
import org.springframework.web.bind.annotation.*;
import java.lang.reflect.Field;

@RestController
public class CacheController{


    @GetMapping("/cache")
    public void myMethod(Person person) { // 使用了自定义注解
        System.out.println("进行调用注解");
        System.out.println(person.getMessage());
        try {
            Field field = Person.class.getDeclaredField("message");
            Cacheable annotation = field.getAnnotation(Cacheable.class);
            if (annotation != null) {
                System.out.println("Message: " + annotation.value());
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

备注:在注解的使用中,在程序运行中不太明显观察注解的用法,因为注解本身就作为一种提示标记。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

code_idea

感谢大佬

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

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

打赏作者

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

抵扣说明:

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

余额充值