国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 Java java教程 Spring Boot 備忘單

Spring Boot 備忘單

Nov 26, 2024 am 12:37 AM

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 首先加載應(yīng)用程序?qū)傩院妥詣优渲?bean。
  2. 組件掃描:Spring 掃描控制器、服務(wù)和存儲庫等組件。
  3. Bean 創(chuàng)建:Spring 創(chuàng)建 Bean 并使用依賴注入解析依賴關(guān)系。
  4. 請求處理:傳入的 HTTP 請求根據(jù)請求映射映射到控制器方法。
  5. 執(zhí)行:控制器方法處理請求、與服務(wù)交互并返回響應(yīng)。
  6. 響應(yīng)渲染:Spring 將方法返回值轉(zhuǎn)換為適當?shù)?HTTP 響應(yīng)(例如 JSON)。

推薦的文件夾結(jié)構(gòu)

src
├── 主要
│ ├── java
│ │ └── com
│ │ └── 例子
│ │ ├── 控制器
│ │ │ └──MyController.java
│ │ ├── 服務(wù)
│ │ │ └──MyService.java
│ │ └── Application.java
│ └── 資源
│ ├── application.properties
│ └── 模板
│ └──index.html
└── 測試
└── java
└── com
└── 例子
└── 控制器
└── MyControllerTest.java

Spring Boot 備忘單中的錯誤處理

錯誤處理是構(gòu)建健壯應(yīng)用程序的一個關(guān)鍵方面。 Spring Boot 提供了多種優(yōu)雅處理錯誤和異常的機制,確保流暢的用戶體驗。

錯誤類型

  • 客戶端錯誤:無效客戶端請求導(dǎo)致的錯誤,例如 400 Bad Request 或 404 Not Found。
  • 服務(wù)器錯誤:服務(wù)器端發(fā)生的錯誤,例如500內(nèi)部服務(wù)器錯誤。
  • 驗證錯誤:由于輸入無效或數(shù)據(jù)驗證失敗而導(dǎo)致的錯誤。

錯誤處理機制

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);
    }
}

響應(yīng)實體異常處理程序

  • 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

3. 錯誤屬性

  • ErrorAttributes:用于自定義錯誤響應(yīng)內(nèi)容和格式的接口。
  • DefaultErrorAttributes:Spring Boot 提供的默認實現(xiàn)。
@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;
}

}

使用屬性文件

  • application.properties:存儲應(yīng)用程序范圍的屬性,例如服務(wù)器端口、數(shù)據(jù)庫 URL 等
  • 自定義屬性文件:為不同環(huán)境定義自定義屬性文件(例如application-dev.properties)。
  • 訪問屬性:使用@Value注釋或Spring的Environment API訪問屬性。

建筑工程

  • Maven:運行 mvn clean install 來構(gòu)建項目并生成可執(zhí)行 JAR。
  • Gradle:運行 ./gradlew build 來構(gòu)建項目并生成可執(zhí)行 JAR。

附加主題

  • Spring Boot Starters:使用 starters 向項目添加依賴項和自動配置。
  • 日志記錄:使用 Logback、Log4j 或 Java Util Logging 配置日志記錄。
  • 錯誤處理:使用@ControllerAdvice實現(xiàn)全局異常處理。
  • 測試:使用 JUnit、Mockito 和 SpringBootTest 編寫單元測試和集成測試。

以上是Spring Boot 備忘單的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

hashmap和hashtable之間的區(qū)別? hashmap和hashtable之間的區(qū)別? Jun 24, 2025 pm 09:41 PM

HashMap與Hashtable的區(qū)別主要體現(xiàn)在線程安全、null值支持及性能方面。1.線程安全方面,Hashtable是線程安全的,其方法大多為同步方法,而HashMap不做同步處理,非線程安全;2.null值支持上,HashMap允許一個null鍵和多個null值,Hashtable則不允許null鍵或值,否則拋出NullPointerException;3.性能方面,HashMap因無同步機制效率更高,Hashtable因每次操作加鎖性能較低,推薦使用ConcurrentHashMap替

為什么我們需要包裝紙課? 為什么我們需要包裝紙課? Jun 28, 2025 am 01:01 AM

Java使用包裝類是因為基本數(shù)據(jù)類型無法直接參與面向?qū)ο蟛僮?,而實際需求中常需對象形式;1.集合類只能存儲對象,如List利用自動裝箱存儲數(shù)值;2.泛型不支持基本類型,必須使用包裝類作為類型參數(shù);3.包裝類可表示null值,用于區(qū)分未設(shè)置或缺失的數(shù)據(jù);4.包裝類提供字符串轉(zhuǎn)換等實用方法,便于數(shù)據(jù)解析與處理,因此在需要這些特性的場景下,包裝類不可或缺。

JIT編譯器如何優(yōu)化代碼? JIT編譯器如何優(yōu)化代碼? Jun 24, 2025 pm 10:45 PM

JIT編譯器通過方法內(nèi)聯(lián)、熱點檢測與編譯、類型推測與去虛擬化、冗余操作消除四種方式優(yōu)化代碼。1.方法內(nèi)聯(lián)減少調(diào)用開銷,將頻繁調(diào)用的小方法直接插入調(diào)用處;2.熱點檢測識別高頻執(zhí)行代碼并集中優(yōu)化,節(jié)省資源;3.類型推測收集運行時類型信息實現(xiàn)去虛擬化調(diào)用,提升效率;4.冗余操作消除根據(jù)運行數(shù)據(jù)刪除無用計算和檢查,增強性能。

什么是接口中的靜態(tài)方法? 什么是接口中的靜態(tài)方法? Jun 24, 2025 pm 10:57 PM

StaticmethodsininterfaceswereintroducedinJava8toallowutilityfunctionswithintheinterfaceitself.BeforeJava8,suchfunctionsrequiredseparatehelperclasses,leadingtodisorganizedcode.Now,staticmethodsprovidethreekeybenefits:1)theyenableutilitymethodsdirectly

什么是實例初始器塊? 什么是實例初始器塊? Jun 25, 2025 pm 12:21 PM

實例初始化塊在Java中用于在創(chuàng)建對象時運行初始化邏輯,其執(zhí)行先于構(gòu)造函數(shù)。它適用于多個構(gòu)造函數(shù)共享初始化代碼、復(fù)雜字段初始化或匿名類初始化場景,與靜態(tài)初始化塊不同的是它每次實例化時都會執(zhí)行,而靜態(tài)初始化塊僅在類加載時運行一次。

變量的最終關(guān)鍵字是什么? 變量的最終關(guān)鍵字是什么? Jun 24, 2025 pm 07:29 PM

InJava,thefinalkeywordpreventsavariable’svaluefrombeingchangedafterassignment,butitsbehaviordiffersforprimitivesandobjectreferences.Forprimitivevariables,finalmakesthevalueconstant,asinfinalintMAX_SPEED=100;wherereassignmentcausesanerror.Forobjectref

什么是工廠模式? 什么是工廠模式? Jun 24, 2025 pm 11:29 PM

工廠模式用于封裝對象創(chuàng)建邏輯,使代碼更靈活、易維護、松耦合。其核心答案是:通過集中管理對象創(chuàng)建邏輯,隱藏實現(xiàn)細節(jié),支持多種相關(guān)對象的創(chuàng)建。具體描述如下:工廠模式將對象創(chuàng)建交給專門的工廠類或方法處理,避免直接使用newClass();適用于多類型相關(guān)對象創(chuàng)建、創(chuàng)建邏輯可能變化、需隱藏實現(xiàn)細節(jié)的場景;例如支付處理器中通過工廠統(tǒng)一創(chuàng)建Stripe、PayPal等實例;其實現(xiàn)包括工廠類根據(jù)輸入?yún)?shù)決定返回的對象,所有對象實現(xiàn)共同接口;常見變體有簡單工廠、工廠方法和抽象工廠,分別適用于不同復(fù)雜度的需求。

什么是類型鑄造? 什么是類型鑄造? Jun 24, 2025 pm 11:09 PM

類型轉(zhuǎn)換有兩種:隱式和顯式。1.隱式轉(zhuǎn)換自動發(fā)生,如將int轉(zhuǎn)為double;2.顯式轉(zhuǎn)換需手動操作,如使用(int)myDouble。需要類型轉(zhuǎn)換的情況包括處理用戶輸入、數(shù)學(xué)運算或函數(shù)間傳遞不同類型的值時。需要注意的問題有:浮點數(shù)轉(zhuǎn)整數(shù)會截斷小數(shù)部分、大類型轉(zhuǎn)小類型可能導(dǎo)致數(shù)據(jù)丟失、某些語言不允許直接轉(zhuǎn)換特定類型。正確理解語言的轉(zhuǎn)換規(guī)則有助于避免錯誤。

See all articles