JAVA自訂註解SpringAOP

來源:互聯網
上載者:User

標籤:enum   ret   實體類   name   ack   構造器   jdk   aop   放棄   

原文:https://my.oschina.net/wangnian/blog/801348

 

 前言:Annotation(註解)是JDK5.0及以後版本引入的,它的作用就是負責註解其他註解。現在開發過程中大家都已經放棄了傳統的XML配置的方式改為註解的方式,既簡單又簡潔,方便管理和維護。目前引用第三方jar包的註解都是解決技術上的問題,然而我們在工作中也需要通過註解解決業務上的一些問題,所以就得用到自訂註解。

1.自訂一個註解

建立一個 @interface的檔案,則表示這是一個註解類

/* * 自訂註解 */@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documented@Inheritedpublic @interface SecureValid {    String desc() default "身份和安全驗證開始...";}
2.註解的屬性描述2.1 @Target 

用於描述註解的使用範圍(即:被描述的註解可以用在什麼地方),其取值有:

ElementType.CONSTRUCTOR                用於描述構造器。
ElementType.FIELD                                用於描述域。
ElementType.LOCAL_VARIABLE             用於描述局部變數
ElementType.METHOD                          用於描述方法
ElementType.PACKAGE                         用於描述包
ElementType.PARAMETER                     用於描述參數
ElementType.TYPE                                 用於描述類或介面

2.2 @Retention

用於描述註解的生命週期(即:被描述的註解在什麼範圍內有效),其取值有:
RetentionPolicy.SOURCE                        在源檔案中有效(即源檔案保留)。
RetentionPolicy.CLASS                           在 class 檔案中有效(即 class 保留)
RetentionPolicy.RUNTIME                      在運行時有效(即運行時保留)

2.3 @Documented

在預設的情況下javadoc命令不會將我們的annotation產生再doc中去的,所以使用該標記就是告訴jdk讓它也將annotation產生到doc中去

2.4 @Inherited

 比如有一個類A,在他上面有一個標記annotation,那麼A的子類B是否不用再次標記annotation就可以繼承得到

3.Annotation屬性值

有以下三種: 基本類型、數群組類型、枚舉類型

3.1 基本串類型 
public @interface UserdefinedAnnotation {      intvalue();      String name() default "zhangsan";      String address();  }使用:@UserdefinedAnnotation(value=123,name="wangwenjun",address="火星")      public static void main(String[] args) {          System.out.println("hello");      }  }
3.2 數組
public @interface UserdefinedAnnotation {      int[] value();  }  使用:  public class UseAnnotation {            @UserdefinedAnnotation({123})      public static void main(String[] args) {          System.out.println("hello");      }  } 
3.3 枚舉類型
public enum DateEnum {      Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday  }  然後在定義一個annotation  package com.wangwenjun.annatation.userdefined;    public @interface UserdefinedAnnotation {      DateEnum week();  }  使用: public class UseAnnotation {      @UserdefinedAnnotation(week=DateEnum.Sunday)      public static void main(String[] args) {          System.out.println("hello");      }  }
4.使用SpringAOP來增強
import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.core.annotation.Order;import org.springframework.http.HttpStatus;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;import java.util.Date;@Aspect@Componentpublic class Aspect {    private static final Logger logger = LoggerFactory.getLogger(Aspect.class);    //切入點    @Pointcut("@annotation(註解的包路徑)")    public void pointcut() {    }    @Around("pointcut()")    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {            //擷取request            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();          //攔截的實體類        Object target = joinPoint.getTarget();        //攔截的方法名稱        String methodName = joinPoint.getSignature().getName();        //攔截的方法參數        Object[] args = joinPoint.getArgs();        //攔截的放參數類型        Class[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getMethod().getParameterTypes();                         //TODO 處理業務代碼                         //處理完之後允許存取            Object[] args = joinPoint.getArgs();            return joinPoint.proceed(args);    }      }

JAVA自訂註解SpringAOP

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.