PHP程序猿的Spring Boot之旅-Spring Boot項目建立

開篇

每個PHP程序員基本都有一段學JAVA的艱辛之路,無論是正在學JAVA仍是已經放棄學JAVA的猿/媛,都被JAVA折磨過,一樣,我也正在被折磨。。。java

用該系列文章記錄我被折磨後的成果。mysql

學習方法分享

我要分享的學習方法很簡單,一個字:幹git

很簡單粗暴的方式,其實學習最好的方式就是輸出,因此我會常常寫博文,分享我學到的東西,只要把學習到的東西輸出出來,纔會深入。程序員

工具準備

  • Intellij IDEA
  • Navicat
  • Docker

環境準備

  • 搭建完成java環境
  • 搭建完成mysql數據庫

Spring Boot項目搭建

  • 打開IDEA,新建一個項目:

建立項目1

  • 填寫項目參數:

建立項目2

  • 添加spring web starter依賴:

建立項目3

  • 點擊next等待加載依賴完成

建立項目4

出現該頁面證實依賴加載完成。github

編寫代碼

  1. 打開SpringBootStudyDemo1Application文件輸入以下代碼:
package cn.sockstack.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
//使用restful風格的controller
@RestController
public class SpringBootStudyDemo1Application {

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

    //添加'/'路由,輸出hello SockStack!
    @GetMapping("/")
    public String hello() {
        return "hello SockStack!";
    }

}
  1. 添加測試代碼
    spring-boot-study-demo1\src\test\java\cn\sockstack\demo\SpringBootStudyDemo1ApplicationTests.java添加以下代碼:
package cn.sockstack.demo;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootStudyDemo1ApplicationTests {
    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;
    @Before
    public void buildMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testHelloController() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML_VALUE)).andReturn();

        int status = mvcResult.getResponse().getStatus();
        String contentAsString = mvcResult.getResponse().getContentAsString();

        Assert.assertEquals(200, status);
        Assert.assertEquals("hello SockStack!", contentAsString);

    }

}

啓動測試,測試結果:web

https://raw.githubusercontent.com/sockstack/hexo_blog_img/master/spring-boot-study-demo/%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE5.png

測試經過,一樣也能夠在瀏覽器打開127.0.0.1:8080,查看結果spring

更多精彩文章,請關注個人博客 SOCKSTACK,分享個人工做經驗。
相關文章
相關標籤/搜索