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(); } } }
备注:在注解的使用中,在程序运行中不太明显观察注解的用法,因为注解本身就作为一种提示标记。