Annotations are simply configuration, which is a special configuration, and can be replaced with annotations. It then uses reflection to get the information of the annotations.
How to define an annotation
You create a new annotation definition in the IDE, which is structured like this:
package com.nicchagil.exercise.springbootexercise.annotation;public @interface MyFirstAnnotation {}
Then there are about 4 of the above structure plus some configuration, of course, this configuration is added in the form of annotations =_=!
Where is this annotation used
Where this annotation will be applied can be configured as follows:
Keep at what time
When to keep:
Annotations are reflected in the document
@Documented
Whether the subclass inherits annotations from the parent class
@Inherited
Get the information of annotations with reflection
Let's define an annotation first:
package com.nicchagil.exercise.springbootexercise.annotation;import java.lang.annotation.Documented;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)@Documentedpublic @interface PojoPostProcessing { public Class targetClass(); public String[] whiteProperties();}
Use annotations, such as here I set to a method:
@PojoPostProcessing(targetClass=User.class, whiteProperties={"name"}) public List<User> selectXxx(String id) { ...... }
Reflection gets the information for the annotation:
@Test public void test() throws NoSuchMethodException, SecurityException, ClassNotFoundException { Class clazz = Class.forName("com.nicchagil.exercise.springbootexercise.service.UserService"); Method method = clazz.getMethod("selectXxx", String.class); boolean isAnnotationPresent = method.isAnnotationPresent(PojoPostProcessing.class); if (!isAnnotationPresent) { return; } PojoPostProcessing dpp = (PojoPostProcessing)method.getAnnotation(PojoPostProcessing.class); this.logger.info("dpp : {}", dpp); }
Log:
dpp : @com.nicchagil.exercise.springbootexercise.annotation.PojoPostProcessing(targetClass=class com.nicchagil.exercise.springbootexercise.mapper.entity.User, whiteProperties=[name])
Java Essentials Java annotations easy to get started