Spring Boot 學習(一) 快速搭建SpringBoot 項目


快速搭建一個 Spring Boot 項目

部分參考於《深入實踐Spring Boot》、《Spring實戰 第四版》與程序猿DD的有關博客。

參考(嘟嘟獨立博客):http://tengj.top/2017/02/26/springboot1/

 

搭建項目:

創建Spring Boot操作步驟如下:
1.在File菜單里面選擇 New > Project,然后選擇Spring Initializr,接着如下圖一步步操作即可。

項目結構

根據上面的操作已經初始化了一個Spring Boot的框架了,項目結構如下:

如你所見,項目里面基本沒有代碼,除了幾個空目錄外,還包含如下幾樣東西。

    • pom.xml:Maven構建說明文件。
    • Chapter1Application.java:一個帶有main()方法的類,用於啟動應用程序(關鍵)。
    • Chapter1ApplicationTests.java:一個空的Junit測試類,它加載了一個使用Spring Boot字典配置功能的Spring應用程序上下文。
    • application.properties:一個空的properties文件,你可以根據需要添加配置屬性。

------------------------------------------------------------------------------------------分割線------------------------------------------------------------------------------------------------------------------

 

 

Spring Boot 優點

  1. 輕量化
  2. 提供 Spring 框架各種默認配置來簡化項目配置
  3. 內嵌 Web 容器
  4. 沒有冗余代碼生成和XML配置要求

Maven 導包

  • spring-boot-starter:核心模塊,包括了自動配置支持、日志和YAML
  • spring-boot-starter-test:測試模塊,包括JUnit、Hamcrest、Mockito
  • spring-boot-starter-web:Web模塊

開工

一個 Spring Boot 案例應該包括四個部分(主加載類、邏輯實現類、單元測試類、以及資源配置文件)。

1. 資源配置文件:這個文件主要記錄了框架下各種設置;前面,我們提到過 Spring Boot 提供 Spring 的默認設置,所以一開始並不需要對這個文件做任何修改,讓框架內嵌的Web容器加載該文件即可。* 注意:命名為application.properties *,並且默認端口為8080。

2. 主加載類:Spring Boot 框架下,最重要的一個類,也是啟動整個框架的入口。一般有兩種代碼模板,好像也沒有什么區別。這里先寫一種:

@SpringBootApplication 

public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

 3. 邏輯實現類:就是我們提供的服務接口,一般就是我們的Controller層。這里實現一個簡單的”hello world!”的Controller,便於測試。 啟動項目后,訪問 http://localhost:8080/hello 來訪問這個控制器。

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String index(){
        return "hello world!";
    }
}

 

4. 單元測試類:顧名思義,就是一個用來測試我們的邏輯實現類的類。

這里使用 JUnit 模擬一個 http 請求來測試我們的 HelloController。

同時,這里涉及到Spring AOP@Before,有興趣的也可以去查看一下。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration  
//測試環境使用,用來表示測試環境使用的ApplicationContext將是WebApplicationContext類型的
public class ApplicationTest  {

    private MockMvc mvc;

    @Before
    public void setUp() throws Exception{
        //通過MockMvcBuilders.xxxSetup().build()創建一個MockMvc進行測試;
        mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }

    @Test
    public void getHello() throws Exception{
        mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("hello world!")))
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }
    /**
     * 1、mockMvc.perform執行一個請求。
     * 2、MockMvcRequestBuilders.get("XXX")構造一個請求。
     * 3、ResultActions.andExpect添加執行完成后的斷言。
     * 4、ResultActions.andDo添加一個結果處理器,表示要對結果做點什么事情
     *   比如此處使用MockMvcResultHandlers.print()輸出整個響應結果信息。
     * 5、ResultActions.andReturn表示執行完成后返回相應的結果。
     */
}

 最后附上, http 請求響應后的報文。

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /hello
       Parameters = {}
          Headers = {Accept=[application/json]}

Handler:
             Type = qg.fangrui.boot.web.HelloController
           Method = public java.lang.String qg.fangrui.boot.web.HelloController.index()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=ISO-8859-1], Content-Length=[12]}
     Content type = application/json;charset=ISO-8859-1
             Body = hello world!
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM