SpringMVC Annotation自定義註解使用筆記
阿新 • • 發佈:2018-12-30
註解是Java 1.5引入的,目前已被廣泛應用於各種Java框架,如Hibernate,Jersey,Spring。註解相當於是一種嵌入在程式中的元資料,可以使用註解解析工具或編譯器對其進行解析,也可以指定註解在編譯期或執行期有效。
step1:自定義註解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ApiLog {
String type();
String name();
}
- 註解方法不能有引數。
- 註解方法的返回型別侷限於原始型別,字串,列舉,註解,或以上型別構成的陣列。
- 註解方法可以包含預設值。
- 註解可以包含與其繫結的元註解,元註解為註解提供資訊,有四種元註解型別:
1. @Documented – 表示使用該註解的元素應被javadoc或類似工具文件化,它應用於型別宣告,型別宣告的註解會影響客戶端對註解元素的使用。如果一個型別宣告添加了Documented註解,那麼它的註解會成為被註解元素的公共API的一部分。
2. @Target – 表示支援註解的程式元素的種類,一些可能的值有TYPE, METHOD, CONSTRUCTOR, FIELD等等。如果Target元註解不存在,那麼該註解就可以使用在任何程式元素之上。
3. @Inherited – 表示一個註解型別會被自動繼承,如果使用者在類宣告的時候查詢註解型別,同時類宣告中也沒有這個型別的註解,那麼註解型別會自動查詢該類的父類,這個過程將會不停地重複,直到該型別的註解被找到為止,或是到達類結構的頂層(Object)。
4. @Retention – 表示註解型別保留時間的長短,它接收RetentionPolicy引數,可能的值有SOURCE, CLASS, 以及RUNTIME。
step2:定義Aspect
@Aspect @Component public class AnnotationAspect { // @Pointcut("execution(public * com.demo.annotation.AnnotationTest.display(..))") // private void upUserPointCutMethod() { // } // @Around("upUserPointCutMethod()") @Around( value="@annotation(com.demo.annotation.ApiLog)") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { //取method MethodSignature signature=(MethodSignature) pjp.getSignature(); Method targetMethod=signature.getMethod(); //取method上annotation ApiLog apiLog=targetMethod.getAnnotation(ApiLog.class); if(apiLog!=null){ //註解資訊 System.out.println("ApiLog name:"+apiLog.name()+" type:"+ apiLog.type()); } //取parameters Object[] objects = pjp.getArgs(); //取parameters裡的註解 Annotation[][] annotations = targetMethod.getParameterAnnotations(); Object result = pjp.proceed(); return result; } }
step3:
配置spring-controller.xml中
<aop:aspectj-autoproxy proxy-target-class="true" />
<context:component-scan base-package="com.demo.annotation"></context:component-scan>
自定義註解使用與測試
@Component
public class AnnotationTest {
@ApiLog(type = "method", name ="display" )
public void display(){
System.out.println("display");
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-controller.xml");
AnnotationTest injectClass=context.getBean(AnnotationTest.class);
//AnnotationTest injectClass =new AnnotationTest();
injectClass.display();
}
}