Spring Boot 簡介
Spring框架功能很強大,但是就算是一個很簡單的項目,我們也要配置很多東西。因此就有了Spring Boot框架,它的作用很簡單,就是幫我們自動配置。Spring Boot框架的核心就是自動配置,只要存在相應的jar包,Spring就幫我們自動配置。如果默認配置不能滿足需求,我們還可以替換掉自動配置類,使用我們自己的配置。另外,Spring Boot還集成了嵌入式的Web服務器,系統監控等很多有用的功,讓我們快速構建企業及應用程序。
依賴管理是任何復雜項目的關鍵部分。以手動的方式來實現依賴管理不太現實,你得花更多時間,同時你在項目的其他重要方面能付出的時間就會變得越少。
Spring Boot starter 就是為了解決這個問題而誕生的。Starter POM 是一組方便的依賴描述符,您可以將其包含在應用程序中。您可以獲得所需的所有 Spring 和相關技術的一站式服務,無需通過示例代碼搜索和復制粘貼依賴。
我們有超過 30 個 Boot starter — 下文將提到其中一部分。
2、Web Starter
首先,讓我們來看看 REST 服務開發。我們可以使用像 Spring MVC、Tomcat 和 Jackson 這樣的庫,這對于單個應用程序來說是還是存在許多依賴。
Spring Boot starter 通過添加一個依賴來幫助減少手動添加依賴的數量。 因此,不要手動指定依賴,您只需要添加一個 starter 即可,如下所示:
1
2
3
4
|
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> |
現在我們可以創建一個 REST 控制器。為了簡單起見,我們不會使用數據庫,只專注于 REST 控制器:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@RestController public class GenericEntityController{ private List<GenericEntity> entityList = new ArrayList<>(); @RequestMapping ( "/entity/all" ) public List<GenericEntity> findAll(){ return entityList; } @RequestMapping (value = "/entity" , method = RequestMethod.POST) public GenericEntity addEntity(GenericEntity entity){ entityList.add(entity); return entity; } @RequestMapping ( "/entity/findby/{id}" ) public GenericEntity findById( @PathVariable Long id){ return entityList.stream(). filter(entity -> entity.getId().equals(id)). findFirst().get(); } } |
GenericEntity是一個簡單的 bean, id 的類型為 Long , value 為 String 類型。
就是這樣,應用程序可以開始運行了,您可以訪問 http://localhost:8080/springbootapp/entity/all 并檢查控制器是否正常工作。
我們已經創建了一個配置非常少的 REST 應用程序。
3、Test Starter
對于測試,我們通常使用以下組合:Spring Test、JUnit、Hamcrest 和 Mockito。我們可以手動包含所有這些庫,但使用以下 Spring Boot starter 方式可以自動包含這些庫:
1
2
3
4
5
|
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> |
請注意,您不需要指定工件的版本號。Spring Boot 會自動選擇合適的版本 — 您僅需要指定 spring-boot-starter-parent-artifact 的版本。 如果之后您想要升級 Boot 庫和依賴,只需在一個地方升級 Boot 版本即可,它將會處理其余部分。
讓我們來測試一下之前創建的控制器。
測試控制器有兩種方法:
- 使用 mock 環境
- 使用嵌入式 Servlet 容器(如 Tomcat 或 Jetty)
在本例中,我們將使用一個 mock 環境:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@RunWith (SpringJUnit4ClassRunner. class ) @SpringApplicationConfiguration (classes = Application. class ) @WebAppConfiguration public class SpringBootApplicationTest{ @Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc; @Before public void setupMockMvc(){ mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName( "utf8" )); mockMvc.perform(MockMvcRequestBuilders.get( "/entity/all" )). andExpect(MockMvcResultMatchers.status().isOk()). andExpect(MockMvcResultMatchers.content().contentType(contentType)). andExpect(jsonPath( "$" , hasSize( 4 ))); } } |
這里重要的是 @WebAppConfiguration 注解和 MockMVC 是 spring-test 模塊的一部分, hasSize 是一個 Hamcrest matcher, @Before 是一個 JUnit 注解。這些都可以通過導入這一個這樣的 starter 依賴來引入。
4、Data JPA Starter
大多數 Web 應用程序都存在某些持久化 — 常見的是 JPA。
讓我們使用 starter 來開始,而不是手動定義所有關聯的依賴:
1
2
3
4
5
6
7
8
9
|
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> |
請注意,我們對這些數據庫已經有了開箱即用的自動支持:H2、Derby 和 Hsqldb。在我們的示例中,我們將使用 H2。
現在讓我們為實體創建倉儲(repository):
1
|
public interface GenericEntityRepositoryextends JpaRepository<GenericEntity,Long>{} |
現在是測試代碼的時候了。這是 JUnit 測試:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@RunWith (SpringJUnit4ClassRunner. class ) @SpringApplicationConfiguration (classes = Application. class ) public class SpringBootJPATest{ @Autowired private GenericEntityRepository genericEntityRepository; @Test public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK(){ GenericEntity genericEntity = genericEntityRepository.save( new GenericEntity( "test" )); GenericEntity foundedEntity = genericEntityRepository.findOne(genericEntity.getId()); assertNotNull(foundedEntity); assertEquals(genericEntity.getValue(), foundedEntity.getValue()); } } |
我們沒有花時間指定數據庫廠商、URL 連接和憑據。沒有額外所需的配置,這些都受益于 Boot 的默認支持。 但是,如果您需要,可以進行詳細配置。
5、Mail Starter
企業開發中一個非常常見的任務就是發送電子郵件,直接使用 Java Mail API 來處理通常很困難。
Spring Boot starter 屏蔽了這些復雜性 — mail 依賴可以通過以下方式指定:
1
2
3
4
|
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> |
現在我們可以直接使用 JavaMailSender 。讓我們開始編寫一些測試。
為了測試,我們需要一個簡單的 SMTP 服務器。在此例中,我們將使用 Wiser。將其包含到我們的 POM 中:
1
2
3
4
5
6
|
<dependency> <groupId>org.subethamail</groupId> <artifactId>subethasmtp</artifactId> <version> 3.1 . 7 </version> <scope>test</scope> </dependency> |
最新版本的 Wiser 可以在 Maven 中央倉庫 ( http://search.maven.org/#search%7Cga%7C1%7Csubethasmtp)中找到。
以下是測試源碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
@RunWith (SpringJUnit4ClassRunner. class ) @SpringApplicationConfiguration (classes = Application. class ) public class SpringBootMailTest{ @Autowired private JavaMailSender javaMailSender; private Wiser wiser; private String userTo = "user2@localhost" ; private String userFrom = "user1@localhost" ; private String subject = "Test subject" ; private String textMail = "Text subject mail" ; @Before public void setUp() throws Exception { final int TEST_PORT = 25 ; wiser = new Wiser(TEST_PORT); wiser.start(); } @After public void tearDown() throws Exception { wiser.stop(); } @Test public void givenMail_whenSendAndReceived_thenCorrect() throws Exception { SimpleMailMessage message = composeEmailMessage(); javaMailSender.send(message); List<WiserMessage> messages = wiser.getMessages(); assertThat(messages, hasSize( 1 )); WiserMessage wiserMessage = messages.get( 0 ); assertEquals(userFrom, wiserMessage.getEnvelopeSender()); assertEquals(userTo, wiserMessage.getEnvelopeReceiver()); assertEquals(subject, getSubject(wiserMessage)); assertEquals(textMail, getMessage(wiserMessage)); } private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException { return wiserMessage.getMimeMessage().getContent().toString().trim(); } private String getSubject(WiserMessage wiserMessage) throws MessagingException { return wiserMessage.getMimeMessage().getSubject(); } private SimpleMailMessage composeEmailMessage(){ SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(userTo); mailMessage.setReplyTo(userFrom); mailMessage.setFrom(userFrom); mailMessage.setSubject(subject); mailMessage.setText(textMail); return mailMessage; } } |
在測試中, @Before 和 @After 方法負責啟動和停止郵件服務器。
請注意,我們裝配了 JavaMailSender bean — 該 bean 是 由 Spring Boot 自動創建 。
與 Boot 中的其他默認值一樣, JavaMailSender 的 email 設置可以在 application.properties 中自定義:
1
2
3
|
spring.mail.host=localhost spring.mail.port= 25 spring.mail.properties.mail.smtp.auth= false |
我們在 localhost:25 上配置了郵件服務器,不需要身份驗證。
6、結論
在本文中,我們介紹了 Starter,解釋了為什么我們需要它們,并提供了如何在項目中使用它們的示例。
讓我們回顧一下使用 Spring Boot starter 的好處:
- 增加 pom 可管理性
- 生產就緒、測試與依賴配置支持
- 減少項目的整體配置時間
總結
以上所述是小編給大家介紹的Spring Boot Starter的相關知識,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.tuicool.com/articles/6bY7j27