1. 程式人生 > >Spring Boot Starters簡單介紹

Spring Boot Starters簡單介紹

arr extends rest base repos 測試控制 overview 依賴管理 rep

1.概述

依賴管理是任何復雜項目的關鍵方面。手動完成此操作並不理想; 你花在它上面的時間越多,你在項目的其他重要方面所花費的時間就越少。

構建Spring Boot啟動器是為了解決這個問題。Starter POM是一組方便的依賴描述符,您可以在應用程序中包含這些描述符。您可以獲得所需的所有Spring和相關技術的一站式服務,而無需搜索示例代碼並復制粘貼依賴描述符。

有超過30個啟動器 - 讓我們在以下部分中看到它們中的一些。

2.Web Starter(servlet容器)

首先,我們來看看開發REST服務; 我們可以使用像Spring MVC,Tomcat和Jackson這樣的庫 - 對於單個應用程序來說有很多依賴關系。

Spring Boot啟動器可以通過添加一個依賴項來幫助減少手動添加的依賴項的數量。因此,不是手動指定依賴項,而是添加一個啟動器,如以下示例所示:

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-web</artifactId>
4 </dependency>

現在我們可以創建一個REST控制器。為簡單起見,我們使用一個簡單的REST控制器:

 1
@RestController 2 public class GenericEntityController { 3 private List<GenericEntity> entityList = new ArrayList<>(); 4 5 @RequestMapping("/entity/all") 6 public List<GenericEntity> findAll() { 7 return entityList; 8 } 9 10 @RequestMapping(value = "/entity", method = RequestMethod.POST)
11 public GenericEntity addEntity(GenericEntity entity) { 12 entityList.add(entity); 13 return entity; 14 } 15 16 @RequestMapping("/entity/findby/{id}") 17 public GenericEntity findById(@PathVariable Long id) { 18 return entityList.stream(). 19 filter(entity -> entity.getId().equals(id)). 20 findFirst().get(); 21 } 22 }

GenericEntity是一個簡單的bean

就是這樣 - 在應用程序運行時,您可以訪問http://localhost:8080/entity/all並檢查控制器是否正常工作。

我們已經創建了一個具有相當小配置的REST應用程序。so easy

3.測試入門

對於測試,我們通常使用以下一組庫:Spring Test,JUnit,Hamcrest和Mockito(後面兩個主要用於代理、重寫對象進行測試)。我們可以手動包含所有這些庫,但可以使用Spring Boot starter以下列方式自動包含這些庫:

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-test</artifactId>
4     <scope>test</scope>
5 </dependency>

請註意,您無需指定工件的版本號。Spring Boot將確定要使用的版本 - 您需要指定的是spring-boot-starter-parent的版本。如果以後需要升級Boot庫和依賴項,只需在一個地方升級Boot版本,它將負責其余的工作。

讓我們實際測試我們在前一個例子中創建的控制器。

有兩種方法可以測試控制器:

  • 使用模擬環境
  • 使用嵌入式Servlet容器(如Tomcat或Jetty)

在這個例子中,我們將使用模擬環境:

 1 @RunWith(SpringJUnit4ClassRunner.class)
 2 @SpringApplicationConfiguration(classes = Application.class)
 3 @WebAppConfiguration
 4 public class SpringBootApplicationIntegrationTest {
 5     @Autowired
 6     private WebApplicationContext webApplicationContext;
 7     private MockMvc mockMvc;
 8  
 9     @Before
10     public void setupMockMvc() {
11         mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
12     }
13  
14     @Test
15     public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect()
16       throws Exception { 
17         MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
18         MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
19         mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).
20         andExpect(MockMvcResultMatchers.status().isOk()).
21         andExpect(MockMvcResultMatchers.content().contentType(contentType)).
22         andExpect(jsonPath("$", hasSize(4))); 
23     } 
24 }

上面的測試調用/entity/all 端點並驗證JSON響應是否包含4個元素。要通過此測試,我們還必須在控制器類中初始化我們的列表:

 1 public class GenericEntityController {
 2     private List<GenericEntity> entityList = new ArrayList<>();
 3  
 4     {
 5         entityList.add(new GenericEntity(1l, "entity_1"));
 6         entityList.add(new GenericEntity(2l, "entity_2"));
 7         entityList.add(new GenericEntity(3l, "entity_3"));
 8         entityList.add(new GenericEntity(4l, "entity_4"));
 9     }
10     //...
11 }

這裏重要的是@WebAppConfiguration註釋和MockMVCspring-test模塊的一部分,hasSize是一個Hamcrest匹配器,而@Before是一個JUnit註釋。這些都可以通過導入這一個啟動器依賴項來獲得。

4. Data JPA Starter

大多數Web應用程序都有某種持久化方法 - 這通常是JPA。

下面不是手動定義所有相關的依賴項 - 而是改為使用啟動器:

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-data-jpa</artifactId>
4 </dependency>
5 <dependency>
6     <groupId>com.h2database</groupId>
7     <artifactId>h2</artifactId>
8     <scope>runtime</scope>
9 </dependency>

請註意,開箱即用我們至少可以自動支持以下數據庫:H2,Derby和Hsqldb。在我們的例子中,我們將使用H2。

現在讓我們為我們的實體創建存儲庫:(下面一行代碼就完成了jps存儲庫的配置,常用實現方法由jpa框架提供,我們只要繼承接口,指定實體類即可)

1 public interface GenericEntityRepository extends JpaRepository<GenericEntity, Long> {}

是時候測試代碼了。這是JUnit測試:

 1 @RunWith(SpringJUnit4ClassRunner.class)
 2 @SpringApplicationConfiguration(classes = Application.class)
 3 public class SpringBootJPATest {
 4      
 5     @Autowired
 6     private GenericEntityRepository genericEntityRepository;
 7  
 8     @Test
 9     public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
10         GenericEntity genericEntity = 
11           genericEntityRepository.save(new GenericEntity("test"));
12         GenericEntity foundedEntity = 
13           genericEntityRepository.findOne(genericEntity.getId());
14          
15         assertNotNull(foundedEntity);
16         assertEquals(genericEntity.getValue(), foundedEntity.getValue());
17     }
18 }

我們沒有花時間指定數據庫供應商,URL連接和憑據。不需要額外的配置,因為我們從可靠的Boot默認值中受益; 但當然,如有必要,仍可配置所有這些細節。

springboot基於自動配置,如果我們不設置的話,其會根據我們的classpath(如這裏的h2數據庫)自動幫我們初始化一些bean實例(包括數據源)。但是一般有些bean我們還是希望自己實例化,可以增加定制的配置信息。

5. 結論

在本文中,我們概述了Starters,解釋了我們為什麽需要它們,並提供了有關如何在項目中使用它們的示例。

讓我們回顧一下使用Spring Boot啟動器的好處:

  • 增加pom可管理性(無需手動配置各依賴項的版本)
  • 生產就緒,測試和支持的依賴配置(一個starter中包含了該功能所需要的所有包,配置起來簡單方便)
  • 減少項目的總體配置時間

Spring Boot Starters簡單介紹