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; |
制御フロー
- 初期化: Spring Boot は、アプリケーションのプロパティをロードし、Bean を自動構成することによって開始されます。
- コンポーネント スキャン: Spring は、コントローラー、サービス、リポジトリなどのコンポーネントをスキャンします。
- Bean の作成: Spring は Bean を作成し、依存関係注入を使用して依存関係を解決します。
- リクエスト処理: 受信 HTTP リクエストは、リクエスト マッピングに基づいてコントローラー メソッドにマッピングされます。
- 実行: コントローラー メソッドはリクエストを処理し、サービスと対話し、応答を返します。
- レスポンスレンダリング: 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 サイトの他の関連記事を参照してください。

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

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

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

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

java'splatformentencemeansemeansapplicationscanrunonanyplatformwithajvm、「writeonce、runany hwhere。」

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

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

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


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

ドリームウィーバー CS6
ビジュアル Web 開発ツール

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

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

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター
