検索

Spring Boot Cheat Sheet

Spring Boot チートシート

注釈

Annotation Description Example
@SpringBootApplication Marks a class as a Spring Boot application. Enables auto-configuration and component scanning. @SpringBootApplication
@RestController Indicates that a class provides RESTful endpoints. It combines @Controller and @ResponseBody annotations. @RestController
@RequestMapping Maps HTTP requests to handler methods of RESTful controllers. @RequestMapping("/api")
@Autowired Injects dependencies into a Spring bean. It can be used for constructor, setter, or field injection. @Autowired private MyService myService;
@Component Indicates that a class is a Spring-managed component. It is automatically detected during component scanning. @Component
@Repository Marks a class as a Spring Data repository. It handles data access and persistence logic. @Repository
@Service Marks a class as a service component in the business layer. It is used to separate business logic from presentation logic. @Service
@Configuration Indicates that a class provides bean definitions. It is used along with @bean to define beans in Java-based configuration. @Configuration
@Value Injects values from properties files or environment variables into Spring beans. @Value("${my.property}") private String property;

制御フロー

  1. 初期化: Spring Boot は、アプリケーションのプロパティをロードし、Bean を自動構成することによって開始されます。
  2. コンポーネント スキャン: Spring は、コントローラー、サービス、リポジトリなどのコンポーネントをスキャンします。
  3. Bean の作成: Spring は Bean を作成し、依存関係注入を使用して依存関係を解決します。
  4. リクエスト処理: 受信 HTTP リクエストは、リクエスト マッピングに基づいてコントローラー メソッドにマッピングされます。
  5. 実行: コントローラー メソッドはリクエストを処理し、サービスと対話し、応答を返します。
  6. レスポンスレンダリング: Spring はメソッドの戻り値を適切な HTTP レスポンス (JSON など) に変換します。

推奨されるフォルダー構成

ソース
§──メイン
│ §── ジャワ
│ │ └─ com
│ │ └─ 例
│ │ §── コントローラー
│ │ │ └── MyController.java
│ │ §── サービス
│ │ │ └── MyService.java
│ │ └─ Application.java
│ └── 資源
│ §── application.properties
│ └── テンプレート
│ └──index.html
└── テスト
━─ ジャワ
━──com
└── 例
└── コントローラー
━── MyControllerTest.java

Spring Boot チートシートでのエラー処理

エラー処理は、堅牢なアプリケーションを構築する上で重要な側面です。 Spring Boot は、エラーと例外を適切に処理し、スムーズなユーザー エクスペリエンスを保証するためのいくつかのメカニズムを提供します。

エラーの種類

  • クライアント エラー: 400 Bad Request や 404 Not Found など、無効なクライアント リクエストによって引き起こされるエラー。
  • サーバー エラー: 500 Internal Server Error など、サーバー側で発生するエラー。
  • 検証エラー: 無効な入力またはデータ検証の失敗によるエラー。

エラー処理メカニズム

1. コントローラーのアドバイス

  • @ControllerAdvice: Spring MVC でグローバル例外ハンドラーを定義するために使用されるアノテーション。
  • @ExceptionHandler: コントローラー アドバイス内の特定の例外を処理するために使用されるアノテーション。
  • :
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MyException.class)
    public ResponseEntity<errorresponse> handleMyException(MyException ex) {
        ErrorResponse response = new ErrorResponse("My error message");
        return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<errorresponse> handleException(Exception ex) {
        ErrorResponse response = new ErrorResponse("Internal server error");
        return new ResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
</errorresponse></errorresponse>

応答エンティティ例外ハンドラ

  • ResponseEntityExceptionHandler: 一般的な Spring MVC 例外を処理するための基本クラス。
  • オーバーライド: handleMethodArgumentNotValid、handleHttpMessageNotReadable などのメソッドをオーバーライドします。
  • :
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    ErrorResponse response = new ErrorResponse("Validation failed");
    return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}

// Other overrides for handling specific exceptions

</object>

3. エラーの属性

  • ErrorAttributes: エラー応答の内容と形式をカスタマイズするために使用されるインターフェイス。
  • DefaultErrorAttributes: Spring Boot によって提供されるデフォルトの実装。
@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<string object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
    Map<string object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);
    errorAttributes.put("customAttribute", "Custom value");
    return errorAttributes;
}

}
</string></string>

プロパティファイルの使用

  • application.properties: サーバー ポート、データベース URL などのアプリケーション全体のプロパティを保存します。
  • カスタム プロパティ ファイル: さまざまな環境のカスタム プロパティ ファイルを定義します (例: application-dev.properties)。
  • プロパティへのアクセス: @Value アノテーションまたは Spring の環境 API を使用してプロパティにアクセスします。

建築プロジェクト

  • Maven: mvn clean install を実行してプロジェクトをビルドし、実行可能 JAR を生成します。
  • Gradle: ./gradlew build を実行してプロジェクトをビルドし、実行可能 JAR を生成します。

追加のトピック

  • Spring Boot スターター: スターターを使用して、プロジェクトに依存関係と自動構成を追加します。
  • ロギング: Logback、Log4j、または Java Util Logging を使用してロギングを構成します。
  • エラー処理: @ControllerAdvice を使用してグローバル例外処理を実装します。
  • テスト: JUnit、Mockito、SpringBootTest を使用して単体テストと統合テストを作成します。

以上がSpring Boot チートシートの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Javaプラットフォームの独立性:OSの違いJavaプラットフォームの独立性:OSの違いMay 16, 2025 am 12:18 AM

さまざまなオペレーティングシステムでのJavaのパフォーマンスには微妙な違いがあります。 1)JVMの実装は、パフォーマンスとゴミ収集に影響を与えるHotspotやOpenJDKなど、異なります。 2)ファイルシステム構造とパスセパレーターは異なるため、Java標準ライブラリを使用して処理する必要があります。 3)ネットワークプロトコルの差動実装は、ネットワークパフォーマンスに影響します。 4)GUIコンポーネントの外観と動作は、システムによって異なります。標準のライブラリと仮想マシンテストを使用することにより、これらの違いの影響を減らし、Javaプログラムをスムーズに実行できるようにすることができます。

Javaの最高の機能:オブジェクト指向プログラミングからセキュリティまでJavaの最高の機能:オブジェクト指向プログラミングからセキュリティまでMay 16, 2025 am 12:15 AM

JavaOffersObustObject-OrientedProgramming(OOP)andTop-notchsecurityfeatures.1)oopinjavaincludesclasses、オブジェクト、継承、多型、老coluste、および有効化の有効化

JavaScript vs Javaの最良の機能JavaScript vs Javaの最良の機能May 16, 2025 am 12:13 AM

javascriptandjavavedistStrenctsss:javascriptexcelsindynamictypingandasynchronousprogramming、whilejavaisrobustwithstrongopandtyping.1)javascript'sdynamicnatureallowsforrapiddeddevermentand developmentandprototyping、

Javaプラットフォームの独立性:利益、制限、および実装Javaプラットフォームの独立性:利益、制限、および実装May 16, 2025 am 12:12 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM)andbytecode.1)TheJVMinterpretsbytecode,allowingthesamecodetorunonanyplatformwithaJVM.2)BytecodeiscompiledfromJavasourcecodeandisplatform-independent.However,limitationsincludepotentialp

Java:本当の言葉のプラットフォームの独立性Java:本当の言葉のプラットフォームの独立性May 16, 2025 am 12:07 AM

java'splatformentencemeansemeansapplicationscanrunonanyplatformwithajvm、「writeonce、runany hwhere。」

JVMパフォーマンスと他の言語JVMパフォーマンスと他の言語May 14, 2025 am 12:16 AM

jvm'sperformanceiscompetitivewitherruntimes、sped、safety、andproductivityの提供

Javaプラットフォームの独立性:使用の例Javaプラットフォームの独立性:使用の例May 14, 2025 am 12:14 AM

javaachievesplatformedentenceTheThejavavirtualMachine(JVM)、avainwithcodetorunonanyplatformwithajvm.1)codescompiledintobytecode、notmachine-specificcode.2)

JVMアーキテクチャ:Java Virtual Machineに深く飛び込みますJVMアーキテクチャ:Java Virtual Machineに深く飛び込みますMay 14, 2025 am 12:12 AM

thejvmisanabstractcomputingMachineCrucialForrunningJavaProgramsDuetoitsPlatForm-IndopentInterChitecture.Itincludes:1)ClassLoaderForloadingClasses、2)Runtimedataareaforforforatastorage、3)executionEngineWithinterter、Jitcompiler、およびGarbagecolfecolfecolfececolfecolfer

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター