Contents
  1. 1. Spring: the source for modern java
  2. 2. 特点:
  3. 3. 快速入门
    1. 3.1. 先决条件
    2. 3.2. 使用maven构建项目
      1. 3.2.1. 1 访问https://start.spring.io/
      2. 3.2.2. 2 选择Maven Project、Spring Boot版本2.0.7选择依赖,这里选择web,可参考下图所示
      3. 3.2.3. 3 点击Generate Project下载demo压缩包
  4. 4. 将zip包解压缩导入IntelliJ IDEA中
  5. 5. 项目结构解析
  6. 6. 添加web模块以及单元测试模块的maven依赖
  7. 7. 编写controller
  8. 8. 编写单元测试

Spring: the source for modern java

摘自官网https://spring.io/

spring-modern-source

Spring Boot可以让我们轻松的创建独立的,生产级的应用程序,使程序变得更加轻量化。你可以 “just run”。你可以依靠一个Java的main函数来运行一个Spring应用。你也可以把你的应用打包为一个jar文件,通过java -jar来运行你的Spring程序。大多数Spring Boot应用程序只需要很少的Spring配置。

特点:

  • 创建独立的Spring应用程序
  • 内嵌Tomcat、Jetty或者Undertow(无需单独部署war文件)
  • 开箱即用,提供各种默认配置来简化项目配置
  • 没有冗余的代码生成也不需要XML配置
  • 尽可能的自动化配置Spring以及第三方库
  • 提供生产监控功能,例如metrics(指标)、health checks(运行状况检查)和externalized configuration(外部配置)

快速入门

先决条件

jdk 1.8

spring framework 5.x以上

使用maven构建项目

1 访问https://start.spring.io/

2 选择Maven Project、Spring Boot版本2.0.7选择依赖,这里选择web,可参考下图所示

2019-01-06_225027

3 点击Generate Project下载demo压缩包

将zip包解压缩导入IntelliJ IDEA中

项目结构解析

2019-01-06_230659

通过上面一系列的操作,我们已经成功的创建了一个Spring Boot程序。Spring Boot的基础结构共三个文件

  • src/main/java程序入口:DemoApplicatio
  • src/main/resources下的配置文件:application.properties
  • src/test/测试入口:DemoApplicationTests

生成的DemoApplicatioDemoApplicationTests类可以直接运行来启动当前创建的项目,由于目前该项目未配合Web模块,所以程序会在加载完Spring之后结束运行。

添加web模块以及单元测试模块的maven依赖

pom.xml文件中仅需要引入两个模块就行

  • spring-boot-starter-web:核心模块,包括自动配置支持、日志和YAML
  • spring-boot-starter-test:测试模块,包括JUnit、Hamcrest、Mockito
1
2
3
4
5
6
7
8
9
10
11
12
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

编写controller

  • 创建cn.com.bmsmart.controller
  • 创建HelloController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package cn.com.bmsmart.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* <p>Description: </p>
* Created by wusong on 2019-01-07 6:55.
*/
@RestController
public class HelloController {

@GetMapping(value = "/")
public String sayHello() {
return "Hello Spring Boot";
}
}

右键DemoApplication启动main方法,然后打开浏览器,输入http://localhost:8080/可以看到输出了Hello Spring Boot

2019-01-07_070403

编写单元测试

打开的工程的src/test/下的测试入口DemoApplicationTests类。然后编写一个单元测试来mock http请求

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
package cn.com.bmsmart.demo;

import cn.com.bmsmart.demo.controller.HelloController;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoApplicationTests {

@Autowired
private HelloController helloController;

private MockMvc mvc;


@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(helloController).build();
}

@Test
public void contextLoads() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello Spring Boot")));
}

}

通过注入HelloController然后在@Before函数中把mock的对象HelloController传递到MockMvcBuilders.standaloneSetup(helloController).build()中,这样就可以构建我们的单元测试了。

  • 注意引入静态类,让statuscontentequalTo函数可用
1
2
3
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

测试结果

2019-01-07_071527

另外一种用法

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
50
51
52
53
package cn.com.bmsmart.demo;

import cn.com.bmsmart.demo.controller.HelloController;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoApplicationTests {

@Autowired
private HelloController helloController;

private MockMvc mvc;


@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(helloController).build();
}

@Test
public void contextLoads() throws Exception {
// mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
// .andExpect(status().isOk())
// .andExpect(content().string(equalTo("Hello Spring Boot")));

MvcResult mvcResult = mvc.perform(
MockMvcRequestBuilders.get("/")
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
System.out.println(content);
}
}

测试结果

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
2019-01-07 07:29:31.555  INFO 7284 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String cn.com.bmsmart.demo.controller.HelloController.sayHello()
2019-01-07 07:29:31.595 INFO 7284 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext@623ebac7
2019-01-07 07:29:31.616 INFO 7284 --- [ main] o.s.mock.web.MockServletContext : Initializing Spring FrameworkServlet ''
2019-01-07 07:29:31.616 INFO 7284 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization started
2019-01-07 07:29:31.617 INFO 7284 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization completed in 1 ms

MockHttpServletRequest:
HTTP Method = GET
Request URI = /
Parameters = {}
Headers = {Accept=[application/json]}
Body = <no character encoding set>
Session Attrs = {}

Handler:
Type = cn.com.bmsmart.demo.controller.HelloController
Method = public java.lang.String cn.com.bmsmart.demo.controller.HelloController.sayHello()

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=[17]}
Content type = application/json;charset=ISO-8859-1
Body = Hello Spring Boot
Forwarded URL = null
Redirected URL = null
Cookies = []
Hello Spring Boot
Contents
  1. 1. Spring: the source for modern java
  2. 2. 特点:
  3. 3. 快速入门
    1. 3.1. 先决条件
    2. 3.2. 使用maven构建项目
      1. 3.2.1. 1 访问https://start.spring.io/
      2. 3.2.2. 2 选择Maven Project、Spring Boot版本2.0.7选择依赖,这里选择web,可参考下图所示
      3. 3.2.3. 3 点击Generate Project下载demo压缩包
  4. 4. 将zip包解压缩导入IntelliJ IDEA中
  5. 5. 项目结构解析
  6. 6. 添加web模块以及单元测试模块的maven依赖
  7. 7. 编写controller
  8. 8. 编写单元测试