首頁> Java> java教程> 主體

在 Spring Boot 中建立自訂註解的終極指南

PHPz
發布: 2024-08-25 18:01:02
原創
411 人瀏覽過

The Ultimate Guide to Create Custom Annotations in Spring Boot
這樣的註解充滿了 Spring Boot 中的整個專案。

但是你知道這些註解解決了什麼問題嗎?

為什麼要引入自訂註解?

如何建立自訂註解?

今天,我將介紹:

  • 為什麼要建立自訂註解?
  • 使用這些註解的主要好處是什麼?
  • 如何建立自訂註解?
  • 註解方法是如何被呼叫的?
  • 什麼時候使用自訂註解?
  • 什麼時候不應該使用自訂註解?
  • 使用自訂註解有哪些缺點?

?為什麼要建立自訂註解?

在 Spring Boot 中,註解不僅僅是添加元資料的一種方式。他們

  • 簡化複雜的任務
  • 減少樣板代碼
  • 增強程式碼可讀性

在 Spring 引入自訂註解之前,開發人員必須使用 XML 設定檔來管理電子郵件驗證等配置。

XML 設定將定義 bean、驗證器和其他必要的元件來執行驗證電子郵件地址等任務。

以下是如何在 Spring 應用程式中使用 XML 設定電子郵件驗證的範例:

The Ultimate Guide to Create Custom Annotations in Spring Boot

如您所見,這很容易成為一場噩夢,因為有數百個類,其中許多類相互依賴。

這也意味著開發人員每次必須新增新的依賴項時都必須尋找此 XML。

自訂註解的主要優點

簡化配置

Spring 引入了自訂註解來簡化配置,允許開發人員直接在程式碼中使用註解。

這減少了對大量 XML 配置的需求,使程式碼庫更乾淨且更易於維護。

支援聲明式編程

Spring 中的自訂註解啟用了聲明式方法。

開發者可以使用@Transactional、@Cacheable或@Scheduled等註解來聲明所需的行為,而無需編寫底層邏輯。

這會產生更具可讀性和可維護性的程式碼。

處理跨領域問題

Spring 的自訂註解通常與面向切面程式設計(AOP)一起使用,允許開發人員集中處理橫切關注點。

例如,@Transactional 註解可以跨多個方法或類別管理事務,而無需將事務管理邏輯分散在整個程式碼中。

減少樣板程式碼

它透過封裝常見行為減少了對樣板程式碼的需求。

例如,@Autowired 註解簡化了依賴注入,允許 Spring 自動注入依賴,而不需要明確的建構子或 setter 方法

是否應該使用 @Autowired 這是一個不同的討論。

提高程式碼可讀性和一致性

Spring 透過將配置和橫切關注點抽象化為註解,提高了程式碼的可讀性。

您和您的同行開發人員可以透過查看方法或類別的註解來快速了解方法或類別的用途,並且註解有助於增強整個程式碼庫的一致性。

框架靈活性和可擴展性

自訂註釋可讓開發人員根據特定需求建立客製化的註釋,從而以標準化的方式擴展框架的功能。

這種靈活性可幫助 Spring 在多個應用程式和架構中保持相關性和強大功能。

?如何建立自訂註釋

第 1 步:定義註釋

  • 透過定義介面創建新的註解。
  • 使用@interface來聲明它。
  • 加入元註解來指定註解的行為方式。
雷雷
  • @Target:指示可以使用註解的位置(例如方法、類別)。
  • @Retention:表示註解保留多久(例如,執行時間、編譯時)。

步驟 2:建立一個面向來處理註釋

您可以使用 Spring 的 BeanPostProcessor、Aspect 或自訂註解處理邏輯來建立自訂邏輯來處理註解。

雷雷

第 3 步:應用註釋

將自訂註解套用到定義的方法、欄位或類別。

package co.officegeek.tokenratelimiter; import org.springframework.stereotype.Service; @Service public class TestService { @LogExecutionTime public void serve() throws InterruptedException { // Simulate some work Thread.sleep(2000); } }
登入後複製

How It Works:

  • The @LogExecutionTime annotation doesn't cause any method to be called directly.
  • The Spring AOP framework detects that a method has the @LogExecutionTime annotation using reflection.
  • The LogExecutionTimeAspect aspect is configured to apply around advice when a method with the @LogExecutionTime annotation is called.
  • The logExecutionTime method in the aspect is executed before and after the annotated method (serve), logging the execution time.

The Ultimate Guide to Create Custom Annotations in Spring Boot


How does the annotated method get invoked?

When you apply a custom annotation to a method, class, or field, the annotation itself doesn't directly cause any method to be called.

Instead, the logic associated with the annotation is typically implemented using reflection or aspect-oriented programming (AOP) in frameworks like Spring.

Here's a breakdown of how the compiler and runtime environment know what method to call when an annotation is applied:

1. Compile-Time Processing (Annotation Processors)

Some annotations are handled at compile time by annotation processors.

Java's javax.annotation.processing package allows developers to create custom annotation processors that generate code, validate annotations, or even modify the abstract syntax tree (AST) of the code being compiled.

The annotation processor reads the annotations during compilation and executes code based on those annotations.

This can include generating new classes or methods that the code will use later.

The @Override annotation is a compile-time annotation that doesn't invoke a method but instead tells the compiler to check if the method actually overrides a superclass method.

How It Works:

  • You define a custom annotation processor by extending AbstractProcessor and overriding the process method.
  • The processor will be invoked by the compiler when it encounters your annotation, allowing you to generate code or perform other tasks.

2. Runtime Processing (Reflection)

Custom annotations can be processed at runtime using reflection.

The runtime system (e.g., a framework like Spring) uses reflection to detect the presence of annotations on methods, classes, or fields, and then applies the corresponding behavior.

A custom annotation like @LogExecutionTime doesn't directly trigger any method call.

Instead, an aspect or some other reflective mechanism checks for the presence of the annotation at runtime and then wraps the method call with additional logic.

How It Works:

  • At runtime, you use Java's reflection API to check if a method or class has a specific annotation using methods like isAnnotationPresent.
  • Once detected, you can invoke methods or execute logic associated with that annotation. For example, if a method has a @LogExecutionTime annotation, you might measure the time before and after the method call.

3. Aspect-Oriented Programming (AOP)

In frameworks like Spring, AOP is commonly used to handle custom annotations.

AOP allows you to define "aspects" that can intercept method calls and perform additional processing before or after the method execution.

When the AOP framework (e.g. Spring AOP) detects an annotation, it triggers the execution of an advice method associated with the aspect.

This advice method contains the logic that the AOP framework executes when the annotated method is called.

A @Transactional annotation in Spring doesn't execute any logic by itself.

Instead, the Spring framework's AOP infrastructure intercepts calls to methods annotated with @Transactional and wraps them with transaction management logic.

How It Works:

  • You define an aspect class with advice methods that are associated with specific pointcuts (join points where you want to apply the advice).
  • The aspect uses annotations like @Around or @Before to specify when the advice should be executed.
  • The AOP framework ensures that when a method with a custom annotation is called, the corresponding advice is executed automatically.

Use Cases Where Custom Annotations Are a Good Approach

Cross-Cutting Concerns

Custom annotations are ideal for handling cross-cutting concerns like logging, security, transaction management, and caching.

These are concerns that affect multiple parts of an application but are not related to the core business logic.

上記の @LogExecutionTime アノテーションは、すべてのメソッドで使用でき、ビジネス ロジックを持たないため、良い例です。

宣言型プログラミング

どのように起こるかではなく、何が起こるかを指定したい場合、カスタム注釈を使用すると、これを行うためのクリーンで表現力豊かな方法が提供されます。

@Cacheable や @Retry のようなアノテーションを使用すると、開発者は実装コードを手動で記述することなく、宣言的にキャッシュを有効にしたり、ロジックを再試行したりできます。

フレームワークまたはライブラリの統合

カスタム アノテーションは、使いやすいアノテーションの背後にある複雑さを隠すことで、フレームワークやライブラリの統合を簡素化できます。

Spring の @Autowired のようなアノテーションは、依存関係を手動でインスタンス化することなく注入するのに役立ちます。

複雑なロジックのカプセル化

複雑なロジックを再利用可能な方法でカプセル化する必要がある場合、カスタム アノテーションは、このロジックを適用するためのクリーンな API を提供できます。

@RateLimit のようなアノテーションは、メソッドの本体をこのロジックで混乱させることなく、メソッドの呼び出し回数を制限するロジックをカプセル化できます。

カスタム アノテーションを使用すべきではないユースケース

シンプルまたは一回限りのロジック

ロジックが単純な場合、または 1 か所にのみ適用する必要がある場合、カスタム アノテーションの作成は過剰であり、コードが不必要に複雑になる可能性があります。

動的な動作を必要とするロジック

アノテーションはコンパイル時に静的に定義されるため、実行時に動作を動的に決定する必要があるシナリオには適していません。

ユーザー入力または外部構成に基づいてメソッドの動作が変更される必要がある場合、カスタム アノテーションを使用してこれを処理すると、複雑な解決策につながる可能性があります。

ビジネスロジック

コア ビジネス ロジックをカスタム アノテーションに抽象化しないでください。これにより、ロジックの透明性が低下し、保守が困難になる可能性があります。

@ProcessOrder などのビジネス プロセスをカプセル化するためにアノテーションを使用すると、重要なビジネス ルールが隠蔽され、コードの理解と保守が困難になる可能性があります。

注釈間の複雑な相互作用

動作が複数のアノテーション間の複雑な相互作用に依存している場合、予期しない結果が生じ、コードの理解とデバッグが困難になる可能性があります。

同じメソッドに影響を与える複数のカスタム アノテーション (@Retry、@Cacheable、@LogExecutionTime など) を組み合わせると、予期しない動作が発生する可能性があり、管理が困難になります

パフォーマンスが重要なコード

カスタム アノテーションはリフレクションまたはプロキシ メカニズムに依存することが多く、パフォーマンスのオーバーヘッドが発生する可能性があります。

パフォーマンスが重要なコードのセクションでは使用しないでください。

カスタム アノテーションを使用して、タイトなループで何百万回も呼び出されるメソッドにログを追加すると、パフォーマンスが大幅に低下する可能性があります。

?概要 - カスタム注釈を使用する場合

カスタム アノテーションは、ロギング、セキュリティ、トランザクション管理などの横断的な問題の処理に最適です。

アプリケーションの複数の部分に同じ動作を適用する必要があるシナリオにも最適です。

ただし、単純な 1 回限りのロジックの場合、またはきめ細かい制御と柔軟性が必要な場合は、カスタム アノテーションが最良のアプローチではない可能性があります。

実装を決定する前にトレードオフを検討してください。

?最終的な考え

カスタム アノテーションは Spring Boot の強力なツールですが、他のツールと同様に、慎重に使用する必要があります。

これらは、反復的なタスクを処理し、コードベース全体で一貫性を確保するためのクリーンで再利用可能な方法を提供します。

ただし、特に複雑さとパフォーマンスに関して、潜在的な欠点に注意してください。

??発表

私は、ソフトウェア開発者と意欲的なマイクロサービスアーキテクトを対象とした、Spring Boot と Bucket4j を使用したレート制限サービスの設計と実装に関する 10 日間のコホートベースのコースを開始します。

次のことを学びます:

✅ 本番環境に対応したマイクロサービスを設計して構築する方法

✅ レート制限アルゴリズムとその実装に関する深い知識

✅ Spring Boot の開発、テスト、コンテナ化のベスト プラクティス

でも、それは

についてでもあります

✅ プロジェクトを特定のタスクに分割する

✅自分自身に責任を持つこと

✅ プロジェクトを適切に設計して構築する

ほとんどの企業に関連するユースケースであるマイクロサービスを設計および開発したいソフトウェア開発者を対象としています。

これは特に、「プロジェクトの経験」はないものの、多大な情熱と野心を持っている、ソフトウェア開発者のキャリアの初期の方に最適です。

これが役立つと思われる場合、または単に詳細を知りたい場合:

ご興味を登録していただければ、ワークショップの詳細をお知らせします。


これは最初に私のサブスタックで公開されました。まず更新情報を入手するには、私の Substack - Weekend Developer を購読してください。

あなたは自分が書いたコードについてのフィードバックが必要な開発者ですか?

それとも、あなたが正しいことをしているかどうかを誰かにレビューしてもらいたいですか?

私は、人々が早期にフィードバックを得て、より良いコードを書けるように、無料のコードレビューセッションを支援しています

Twitter (X) または LinkedIn で私に DM してください。コードについてお手伝いします。

以上是在 Spring Boot 中建立自訂註解的終極指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!