將 Spring Data REST 新增到現有 Spring MVC 應用程式
如果使用 Spring Boot,以下步驟是不必要的。對於 Boot 應用程式,新增 spring-boot-starter-data-rest 會自動將 Spring Data REST 新增到您的應用程式中。 |
您可以將 Spring Data REST 與現有 Spring MVC 應用程式整合。在您的 Spring MVC 配置中(很可能是您配置 MVC 資源的地方),新增一個對負責配置 RepositoryRestController 的 Java 配置類的 bean 引用。該類名為 org.springframework.data.rest.webmvc.RepositoryRestMvcConfiguration。以下示例展示瞭如何使用 @Import 註解新增正確的引用。
配置將如下所示:
import org.springframework.context.annotation.Import;
import org.springframework.data.rest.webmvc.RepositoryRestMvcConfiguration;
@Configuration
@Import(RepositoryRestMvcConfiguration.class)
public class MyApplicationConfiguration {
…
}
<bean class="org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration"/>
當您的 ApplicationContext 遇到此 bean 定義時,它會引導必要的 Spring MVC 資源,以完全配置控制器,匯出它在該 ApplicationContext 和任何父上下文中找到的儲存庫。
更多關於所需配置的資訊
Spring Data REST 依賴於一些 Spring MVC 資源,這些資源必須正確配置才能在現有 Spring MVC 應用程式中執行。我們試圖將這些資源與應用程式中已有的任何類似資源隔離開來,但您可能希望透過修改這些 MVC 元件來定製 Spring Data REST 的某些行為。
您應該特別注意配置 RepositoryRestHandlerMapping,這將在下一節中介紹。
RepositoryRestHandlerMapping
我們註冊了一個自定義的 HandlerMapping 例項,它只響應 RepositoryRestController,並且僅當某個路徑旨在由 Spring Data REST 處理時。為了將旨在由您的應用程式處理的路徑與由 Spring Data REST 處理的路徑分開,這個自定義的 HandlerMapping 類會檢查 URL 路徑,並檢查是否存在以該名稱匯出的儲存庫。如果存在,自定義的 HandlerMapping 類將允許 Spring Data REST 處理該請求。如果不存在以該名稱匯出的儲存庫,它將返回 null,這意味著“讓其他 HandlerMapping 例項嘗試處理此請求”。
Spring Data REST 的 HandlerMapping 配置了 order=(Ordered.LOWEST_PRECEDENCE - 100),這意味著在對映 URL 路徑時,它通常是第一個。您的現有應用程式永遠沒有機會處理旨在用於儲存庫的請求。例如,如果您有一個以 person 名稱匯出的儲存庫,那麼所有以 /person 開頭的應用程式請求都將由 Spring Data REST 處理,您的應用程式永遠不會看到該請求。但是,如果您的儲存庫以不同的名稱匯出(例如 people),那麼對 /people 的請求將轉到 Spring Data REST,而對 /person 的請求將由您的應用程式處理。