欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解SpringBoot如何自定義注解

 更新時(shí)間:2024年08月11日 08:41:45   作者:HBLOG  
注解,也叫元數(shù)據(jù),一種代碼級別的說明,它是JDK1.5及以后版本引入的一個(gè)特性,與類、接口、枚舉是在同一個(gè)層次,本文給大家詳細(xì)介紹了SpringBoot如何自定義注解,文中通過代碼講解的非常詳細(xì),需要的朋友可以參考下

1.什么是注解

注解(Annotation),也叫元數(shù)據(jù)。一種代碼級別的說明。它是JDK1.5及以后版本引入的一個(gè)特性,與類、接口、枚舉是在同一個(gè)層次。它可以聲明在包、類、字段、方法、局部變量、方法參數(shù)等的前面,用來對這些元素進(jìn)行說明,注釋。

元注解

有一些注解可以修飾其他注解,這些注解就稱為元注解(meta annotation)。Java標(biāo)準(zhǔn)庫已經(jīng)定義了一些元注解,我們只需要使用元注解,通常不需要自己去編寫元注解。

@Target

最常用的元注解是@Target。使用@Target可以定義Annotation能夠被應(yīng)用于源碼的哪些位置:

  • 類或接口:ElementType.TYPE
  • 字段:ElementType.FIELD;
  • 方法:ElementType.METHOD
  • 構(gòu)造方法:ElementType.CONSTRUCTOR;
  • 方法參數(shù):ElementType.PARAMETER

例如,定義注解@Report可用在方法上,我們必須添加一個(gè)@Target(ElementType.METHOD)

@Target(ElementType.METHOD)
public @interface Report {
    int type() default 0;
    String level() default "info";
    String value() default "";
}

定義注解@Report可用在方法或字段上,可以把@Target注解參數(shù)變?yōu)閿?shù)組{ ElementType.METHOD, ElementType.FIELD }

@Target({
    ElementType.METHOD,
    ElementType.FIELD
})
public @interface Report {
    ...
}

實(shí)際上@Target定義的valueElementType[]數(shù)組,只有一個(gè)元素時(shí),可以省略數(shù)組的寫法。

@Retention

另一個(gè)重要的元注解@Retention定義了Annotation的生命周期:

  • 僅編譯期:RetentionPolicy.SOURCE
  • 僅class文件:RetentionPolicy.CLASS;
  • 運(yùn)行期:RetentionPolicy.RUNTIME。

如果@Retention不存在,則該Annotation默認(rèn)為CLASS。因?yàn)橥ǔN覀冏远x的Annotation都是RUNTIME,所以,務(wù)必要加上@Retention(RetentionPolicy.RUNTIME)這個(gè)元注解:

@Retention(RetentionPolicy.RUNTIME)
public @interface Report {
    int type() default 0;
    String level() default "info";
    String value() default "";
}

@Repeatable

使用@Repeatable這個(gè)元注解可以定義Annotation是否可重復(fù)。這個(gè)注解應(yīng)用不是特別廣泛。

@Repeatable(Reports.class)
@Target(ElementType.TYPE)
public @interface Report {
    int type() default 0;
    String level() default "info";
    String value() default "";
}

@Target(ElementType.TYPE)
public @interface Reports {
    Report[] value();
}

經(jīng)過@Repeatable修飾后,在某個(gè)類型聲明處,就可以添加多個(gè)@Report注解:

@Report(type=1, level="debug")
@Report(type=2, level="warning")
public class Hello {
}

@Inherited

使用@Inherited定義子類是否可繼承父類定義的Annotation@Inherited僅針對@Target(ElementType.TYPE)類型的annotation有效,并且僅針對class的繼承,對interface的繼承無效:

@Inherited
@Target(ElementType.TYPE)
public @interface Report {
    int type() default 0;
    String level() default "info";
    String value() default "";
}

在使用的時(shí)候,如果一個(gè)類用到了@Report

@Report(type=1)
public class Person {
}

則它的子類默認(rèn)也定義了該注解:

public class Student extends Person {
}

2.代碼工程

實(shí)驗(yàn)?zāi)康?/h3>

實(shí)現(xiàn)統(tǒng)計(jì)方法執(zhí)行時(shí)間的注解

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>annotations</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>

        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
        </dependency>

        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.21</version>
        </dependency>
    </dependencies>
</project>

controller

使用自定義注解@RequestTime

package com.et.annotation.controller;

import com.et.annotation.RequestTime;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloWorldController {
    @RequestMapping("/hello")
   @RequestTime
    public Map<String, Object> showHelloWorld(){
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "HelloWorld");
        return map;
    }
}

custom annotation

自定義@RequestTime注解

package com.et.annotation;

import java.lang.annotation.*;

/**
 * computa the excute time for the method
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface RequestTime {

}

具體的攔截邏輯類

package com.et.annotation;

import com.et.annotation.util.AspectUtil;
import lombok.extern.slf4j.Slf4j;
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.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Slf4j
@Aspect
@Component
public class RequestTimeAspect {



    @Pointcut(value = "@annotation(com.et.annotation.RequestTime)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object handle(ProceedingJoinPoint point) throws Throwable {
      Method currentMethod = AspectUtil.getMethod(point);
      long starttime = System.currentTimeMillis();
      Object result = point.proceed();
      long endtime = System.currentTimeMillis();
      long requesttime =endtime-starttime;
      //if(requesttime>1000){
      log.info(AspectUtil.getClassName(point)+"."+currentMethod.getName()+"execute time:"+requesttime+" ms");
      //}
        return result;
    }
}

以上只是一些關(guān)鍵代碼,所有代碼請參見下面代碼倉庫

代碼倉庫

3.測試

  • 啟動(dòng)Spring Boot應(yīng)用程序

  • 訪問http://127.0.0.1:8088/hello

  • 控制臺輸出 日志

    2024-08-10 19:30:43.670 INFO 3343 --- [nio-8088-exec-1] com.et.annotation.RequestTimeAspect : com_et_annotation_controller_HelloWorldController.showHelloWorldexecute time:41 ms

以上就是詳解SpringBoot如何自定義注解的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot自定義注解的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • springboot如何初始化執(zhí)行sql語句

    springboot如何初始化執(zhí)行sql語句

    這篇文章主要介紹了springboot初始化執(zhí)行sql語句的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • springboot中的RestTemplate使用詳解

    springboot中的RestTemplate使用詳解

    這篇文章主要介紹了springboot中的RestTemplate使用詳解,RestTemplate繼承自InterceptingHttpAccessor并且實(shí)現(xiàn)了RestOperations接口,其中RestOperations接口定義了基本的RESTful操作,這些操作在RestTemplate中都得到了實(shí)現(xiàn),需要的朋友可以參考下
    2023-09-09
  • java中BeanUtils.copyProperties的用法(超詳細(xì))

    java中BeanUtils.copyProperties的用法(超詳細(xì))

    本文介紹了BeanUtils.copyProperties()方法的使用,包括其功能、用法、注意事項(xiàng)和示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-08-08
  • java并發(fā)數(shù)據(jù)包Exchanger線程間的數(shù)據(jù)交換器

    java并發(fā)數(shù)據(jù)包Exchanger線程間的數(shù)據(jù)交換器

    這篇文章主要為大家介紹了java并發(fā)數(shù)據(jù)包使用數(shù)據(jù)交換器Exchanger來進(jìn)行線程之間的數(shù)據(jù)交換。有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2022-03-03
  • Feign遠(yuǎn)程調(diào)用丟失請求頭問題

    Feign遠(yuǎn)程調(diào)用丟失請求頭問題

    本文介紹了在服務(wù)端項(xiàng)目中如何解決資源訪問限制問題,首先介紹了問題的產(chǎn)生,然后詳細(xì)解析了源碼,最后提出了解決方案,解決方案包括同步和異步兩種,同步時(shí)直接向Spring容器注入RequestInterceptor攔截器
    2024-09-09
  • 詳解Spring簡單容器中的Bean基本加載過程

    詳解Spring簡單容器中的Bean基本加載過程

    本篇將對定義在 XMl 文件中的 bean,從靜態(tài)的的定義到變成可以使用的對象的過程,即 bean 的加載和獲取的過程進(jìn)行一個(gè)整體的了解
    2017-05-05
  • SpringCloud之動(dòng)態(tài)刷新、重試、服務(wù)化的實(shí)現(xiàn)

    SpringCloud之動(dòng)態(tài)刷新、重試、服務(wù)化的實(shí)現(xiàn)

    這篇文章主要介紹了SpringCloud 之動(dòng)態(tài)刷新、重試、服務(wù)化的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • SpringBoot+docker環(huán)境變量配置詳解

    SpringBoot+docker環(huán)境變量配置詳解

    這篇文章主要介紹了SpringBoot+docker環(huán)境變量配置詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • Dubbo服務(wù)校驗(yàn)參數(shù)的解決方案

    Dubbo服務(wù)校驗(yàn)參數(shù)的解決方案

    這篇文章主要介紹了Dubbo服務(wù)如何優(yōu)雅的校驗(yàn)參數(shù),Dubbo框架本身是支持參數(shù)校驗(yàn)的,同時(shí)也是基于JSR303去實(shí)現(xiàn)的,今天通過示例代碼介紹下詳細(xì)實(shí)現(xiàn)過程,需要的朋友可以參考下
    2022-03-03
  • idea激活A(yù)ctivateJrebel熱部署的方法詳解

    idea激活A(yù)ctivateJrebel熱部署的方法詳解

    這篇文章主要介紹了idea激活A(yù)ctivateJrebel熱部署的方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11

最新評論