# Spring Boot

## 序

參考資料:(<https://kknews.cc/code/ebjoajz.html>)

參考資料:(<https://blog.csdn.net/sifanlook/article/details/88905090>)

當新建一個 Spring Boot 項目時，就會有一個 `Application.java` 了

只要再產生一個 `Controller.java` 就可以跑起來一個最簡單的 RESTful 伺服器了

以前是用 `@Controller`

如果要返回 json 要配合 `@ResponseBody`

Spring4 之後 加入 `@RestController` 就夠了

也就是說 `@RestController` = `@Controller` + `@ResponseBody`\ <br>

@CrossOrigin(origins = "[http://localhost:4200")\\](https://brianwu.gitbook.io/brian/java/spring/http:/localhost:4200"\)\\)
可以利用這個去允許特定前端存取

參考資料:(<https://blog.csdn.net/sinat_23225111/article/details/77984206>)

在 Controller 裡面配置 url 映射是用 `@RequestMapping`

這邊就可以去參考章節 \<RequestParameter>

如果需要重定向，可以回傳 `ModelAndView`

如果需要重定向，可以傳入 `HttpServletResponse`，再 `sendRedirect()`

參考資料:(<https://www.baeldung.com/spring-boot-starters>)

spring boot 的 starter 可以幫助我們 **減少相依套件的管理、配置時間**

## 用資料夾切割架構

Controller - Service - Model - DAO - DB

handler

exception

utility

## @SpringCloudApplication和@SpringBootApplication的區別

參考資料:(<https://blog.csdn.net/tt____tt/article/details/81080200>)

@SpringCloudApplication包括：\
@SpringBootApplication、@EnableDiscoveryClient、@EnableCircuitBreaker，\
分別是SpringBoot注解、註冊服務中心Eureka注解、斷路器注解。

對於 SpringCloud 来说，這是每一微服務必須應有的三個注解，所以才推出了 @SpringCloudApplication 這一注解集合。

## @Scope

參考資料:(<https://kknews.cc/zh-tw/code/zbvkozl.html>)

&#x20;Spring容器最初提供了兩種bean的scope類型：singleton和prototype；但發布2.0以後，又引入了另外三種scope類型：request、session和global session,這三種只能在web 應用中才可以使用。

### singleton(默認)

&#x20;這是Spring默認的scope，表示Spring容器只創建唯一一個bean的實例，所有該對象的引用都共享這個實例，並且Spring在創建第一次後，會在Spring的IoC容器中緩存起來，之後不再創建，就是設計模式中的單例模式的形式。

&#x20;並且對該bean的所有後續請求和引用都將返回該緩存中的對象實例。一般情況下，**無狀態的bean使用該scope**。

### **prototype：**

代表線程每次調用或請求這個bean都會創建一個新的實例。一般情況下，有狀態的bean使用該scope。

### **request：**

每次http請求將會有各自的bean實例，類似於prototype。

也就是說每個request作用域內的請求只創建一個實例。

### **session：**

在一個http session中，一個bean定義對應一個bean實例。也就是說每個session作用域內的請求只創建一個實例。<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://brianwu.gitbook.io/brian/java/spring/spring-boot.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
