- 访问:
http://start.spring.io/
选择构建工具
Maven Project
、Spring Boot版本2.0.0
以及一些工程基本信息,可参考下图所示(选了Web)点击
Generate Project
下载项目压缩包- 导入到你的工程,如果是IDEA,则需要:
a.菜单中选择File
–>New
–>Project from Existing Sources...
b.选择解压后的项目文件夹,点击OK
c.点击Import project from external model
并选择Maven
,点击Next
到底为止。
d.若你的环境有多个版本的JDK,注意到选择Java SDK
的时候请选择Java 7
以上的版本
请记得选择File->Project Structure->Project->Project SDK选择上sdk
添加controller目录,然后添加HelloWorldController控制器
package com.wym.helloworld.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@RequestMapping(value = "/hello")
public String index() {
return "Hello World";
}
}
添加代码,@RestController
的意思就是controller里面的方法都以json格式输出
启动HelloworldApplication,这是整个程序入口
成功启动如下
访问http://localhost:8080/hello即可看到效果啦
添加单元测试
使用mockmvc进行,利用MockMvcResultHandlers.print()打印出执行结果。
package com.wym.helloworld;
import com.wym.helloworld.controller.HelloWorldController;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloworldApplicationTests {
private MockMvc mvc;
@Before
public void setUp() {
mvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
}
@Test
public void contextLoads() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("Hello World")));
}
}
测试通过
参考:
- http://www.ityouknow.com/springboot/2016/01/06/springboot(%E4%B8%80)-%E5%85%A5%E9%97%A8%E7%AF%87.html
- http://tengj.top/2017/02/26/springboot1/