標籤:ati users his get gil pos first xxx 定義
註解簡單來說就是配置,是特別的配置,之前常用的設定檔,可以用註解替換。然後通過反射去擷取註解的資訊。
如何定義一個註解
你在IDE中建立一個註解定義,是這樣的結構的:
package com.nicchagil.exercise.springbootexercise.annotation;public @interface MyFirstAnnotation {}
然後大概有4個對上述結構加上一些配置,當然,這配置是以註解的形式添加的=_=!
此註解使用在哪裡
此註解會應用的哪裡,可通過如下配置:
保留在什麼時候
保留到什麼時候:
註解體現在文檔中
@Documented
子類是否繼承父類的註解
@Inherited
用反射擷取註解的資訊
我們先定義一個註解:
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();}
使用註解,比如這裡我設定到一個方法上:
@PojoPostProcessing(targetClass=User.class, whiteProperties={"name"}) public List<User> selectXxx(String id) { ...... }
反射擷取註解的資訊:
@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); }
日誌:
dpp : @com.nicchagil.exercise.springbootexercise.annotation.PojoPostProcessing(targetClass=class com.nicchagil.exercise.springbootexercise.mapper.entity.User, whiteProperties=[name])
【Java基礎】Java註解簡單入門