|
| 1 | +--- |
| 2 | +title: Springboot 系列(一)Spring Boot 入门篇 |
| 3 | +toc_number: false |
| 4 | +date: 2019-01-01 15:14:17 |
| 5 | +url: springboot/springboot01-quick-start |
| 6 | +tags: |
| 7 | +- Springboot |
| 8 | +categories: |
| 9 | +- Springboot |
| 10 | +--- |
| 11 | + |
| 12 | + |
| 13 | +> 注意:本 Spring Boot 系列文章基于 Spring Boot 版本 **v2.1.1.RELEASE** 进行学习分析,版本不同可能会有细微差别。 |
| 14 | +
|
| 15 | +## 前言 |
| 16 | + |
| 17 | + |
| 18 | + |
| 19 | +由于 J2EE 的开发变得笨重,繁多的配置,错乱的依赖管理,低下的开发效率,复杂的部署流程,第三方技术的集成难度较大等。同时随着复杂项目的演进,微服务分布式架构思想逐渐进入开发者的视野。 |
| 20 | + |
| 21 | +## 1. Spring Boot 介绍 |
| 22 | +`Spring Boot` 提供了一组工具只需要极少的配置就可以快速的构建并启动基于 Spring 的应用程序。解决了传统 Spring 开发需要配置大量配置文件的痛点,同时 `Spring Boot` 对于第三方库设置了合理的默认值,可以快速的构建起应用程序。当然 `Spring Boot` 也可以轻松的自定义各种配置,无论是在开发的初始阶段还是投入生成的后期阶段。 |
| 23 | + |
| 24 | +<!-- more --> |
| 25 | +## 2. Spring Boot 优点 |
| 26 | +- 快速的创建可以独立运行的 Spring 项目以及与主流框架的集成。 |
| 27 | +- 使用嵌入式的 Servlet 容器,用于不需要打成war包。 |
| 28 | +- 使用很多的启动器(Starters)自动依赖与版本控制。 |
| 29 | +- 大量的自动化配置,简化了开发,当然,我们也可以修改默认值。 |
| 30 | +- 不需要配置 XML 文件,无代码生成,开箱即用。 |
| 31 | +- 准生产环境的运行时应用监控。 |
| 32 | +- 与云计算的天然集成。 |
| 33 | + |
| 34 | + |
| 35 | +## 3. Spring Boot 前置 |
| 36 | +说了那么多的 Spring Boot 的好处,那么使用 Spring Boot 需要哪些前置知识呢?我简单列举了一下。 |
| 37 | +- Spring 框架的使用。 |
| 38 | +- Maven 构建工具的使用。 |
| 39 | +- IDEA 或其他开发工具的使用。 |
| 40 | + |
| 41 | +## 4. Spring Boot 体验 |
| 42 | +现在我们已经了解了 Spring Boot 是什么,下面我们将使用 Spring Boot 开发一个入门案例,来体验 Spring Boot 开发姿势是如何的优雅与迅速。 |
| 43 | +Spring Boot 官方已经为我们如何快速启动 Spring Boot 应用程序提供了多种方式。 |
| 44 | + |
| 45 | +你可以在 Spring 官方网站直接生成项目下载导入IDE进行开发。 |
| 46 | + |
| 47 | +> https://start.spring.io/ |
| 48 | +
|
| 49 | +也可以直接克隆 GitHub 上的初始项目进行体验。 |
| 50 | + |
| 51 | +```shell |
| 52 | +git clone https://github.com/spring-guides/gs-spring-boot.git |
| 53 | +cd gs-spring-boot/initial |
| 54 | +``` |
| 55 | + |
| 56 | +这里我们选择后者,直接克隆进入到 initial 文件夹使用 maven 进行编译启动。 |
| 57 | + |
| 58 | +```shell |
| 59 | + mvn package && java -jar target/gs-spring-boot-0.1.0.jar |
| 60 | +``` |
| 61 | + |
| 62 | +第一次编译需要下载需要的依赖,耗时会比较长,编译完成之后紧接着可以看到 Spring 的启动标志。这时 Spring Boot 的 web程序已经运行在8080端口了。 |
| 63 | + |
| 64 | +```shell |
| 65 | +$ curl -s localhost:8080 |
| 66 | +Greetings from Spring Boot! |
| 67 | +``` |
| 68 | + |
| 69 | +## 5. Spring Boot 开发 |
| 70 | + |
| 71 | +下面手动编写一个 Spring Boot 入门案例,快速的开发一个 web mvc 应用。 |
| 72 | +项目结构如下: |
| 73 | + |
| 74 | + |
| 75 | + |
| 76 | +### 5.1 依赖项 |
| 77 | + |
| 78 | +```xml |
| 79 | + |
| 80 | + <parent> |
| 81 | + <groupId>org.springframework.boot</groupId> |
| 82 | + <artifactId>spring-boot-starter-parent</artifactId> |
| 83 | + <version>2.1.1.RELEASE</version> |
| 84 | + <relativePath/> <!-- lookup parent from repository --> |
| 85 | + </parent> |
| 86 | + |
| 87 | + <dependencies> |
| 88 | + <dependency> |
| 89 | + <groupId>org.springframework.boot</groupId> |
| 90 | + <artifactId>spring-boot-starter-web</artifactId> |
| 91 | + </dependency> |
| 92 | + |
| 93 | + <dependency> |
| 94 | + <groupId>org.springframework.boot</groupId> |
| 95 | + <artifactId>spring-boot-starter-test</artifactId> |
| 96 | + <scope>test</scope> |
| 97 | + </dependency> |
| 98 | + |
| 99 | + </dependencies> |
| 100 | + |
| 101 | + <build> |
| 102 | + <plugins> |
| 103 | + <plugin> |
| 104 | + <groupId>org.springframework.boot</groupId> |
| 105 | + <artifactId>spring-boot-maven-plugin</artifactId> |
| 106 | + </plugin> |
| 107 | + </plugins> |
| 108 | + </build> |
| 109 | +``` |
| 110 | + |
| 111 | +`spring-boot-starter-parent` 是Spring Boot 的核心依赖,它里面定义了各种在开发中会用到的第三方 jar 的版本信息,因此我们在引入其他的 Spring Boot 为我们封装的启动器的时候都不在需要指定版本信息。如果我们需要自定义版本信息,可以直接覆盖版本属性值即可。 |
| 112 | + |
| 113 | +`spring-boot-starter-web` 提供 web 以及 MVC 和 validator 等web开发框架的支持。 |
| 114 | + |
| 115 | +`spring-boot-starter-test` 提供测试模块的支持。如 Junit,Mockito。 |
| 116 | + |
| 117 | +需要说明的是,Spring Boot 为我们提供了很多的已经封装好的称为启动器(starter)的依赖项。让我们在使用的时候不需要再进行复杂的配置就可以迅速的进行应用集成。所有的官方启动器依赖可以在[这里](https://github.com/spring-projects/spring-boot/tree/v2.1.1.RELEASE/spring-boot-project/spring-boot-starters)查看。 |
| 118 | + |
| 119 | +> 所有**官方**发布的启动器都遵循类似的命名模式; `spring-boot-starter-*`,这里`*`是指特定类型的应用程序。此命名结构旨在帮助您寻找启动器。 |
| 120 | +> |
| 121 | +> 注意:编写自己的启动器的时候不应该使用这种命名方式。 |
| 122 | +
|
| 123 | +### 5.2 启动类 |
| 124 | + |
| 125 | +```java |
| 126 | +@SpringBootApplication |
| 127 | +public class HelloApplication { |
| 128 | + |
| 129 | + public static void main(String[] args) { |
| 130 | + SpringApplication.run(HelloApplication.class, args); |
| 131 | + } |
| 132 | + |
| 133 | + @Bean |
| 134 | + public CommandLineRunner commandLineRunner(ApplicationContext ctx) { |
| 135 | + return args -> { |
| 136 | + // 开始检查spring boot 提供的 beans |
| 137 | + System.out.println("Let's inspect the beans provided by Spring Boot:"); |
| 138 | + String[] beanNames = ctx.getBeanDefinitionNames(); |
| 139 | + Arrays.sort(beanNames); |
| 140 | + for (String beanName : beanNames) { |
| 141 | + System.out.println(beanName); |
| 142 | + } |
| 143 | + }; |
| 144 | + } |
| 145 | +} |
| 146 | + |
| 147 | +``` |
| 148 | + |
| 149 | +`@SpringBootApplication` 注解是一个便利的注解,它包含了以下几个注解。 |
| 150 | + |
| 151 | +1. `@Configuration` 定义配置类。 |
| 152 | + |
| 153 | +2. `@EnableAutoConfiguration` 开启自动配置。 |
| 154 | + |
| 155 | +3. `@EnableWebMvc` 标记为 web应用程序。 |
| 156 | + |
| 157 | +4. `@ComponentScan` 组件扫描。 |
| 158 | + |
| 159 | +### 5.3 控制器 |
| 160 | + |
| 161 | +```java |
| 162 | +@RestController |
| 163 | +public class HelloController { |
| 164 | + @RequestMapping("/") |
| 165 | + public String index() { |
| 166 | + return "Greetings from Spring Boot!"; |
| 167 | + } |
| 168 | +} |
| 169 | +``` |
| 170 | + |
| 171 | +`@RestController` 是 `@Controller` 与 `@ResponseBody` 的结合体。 |
| 172 | + |
| 173 | +### 5.4 访问测试 |
| 174 | + |
| 175 | +直接启动 `HelloApplication.java` 类就可以在控制台看到启动输出,然后访问8080端口查看启动是否正常。 |
| 176 | + |
| 177 | + |
| 178 | + |
| 179 | +经过上面的例子,已经使用 Spring Boot 快速的创建了一个 web 应用并进行了简单的访问测试。 |
| 180 | + |
| 181 | +## 6. Spring Boot 单元测试 |
| 182 | + |
| 183 | +结合上面提到的 Spring Boot 启动器知识,Spring Boot 已经为我们提供了丰富的第三方框架,测试框架也不例外。 |
| 184 | + |
| 185 | +导入单元测试依赖。 |
| 186 | + |
| 187 | +```java |
| 188 | + <dependency> |
| 189 | + <groupId>org.springframework.boot</groupId> |
| 190 | + <artifactId>spring-boot-starter-test</artifactId> |
| 191 | + <scope>test</scope> |
| 192 | + </dependency> |
| 193 | +``` |
| 194 | + |
| 195 | +### 6.1 模拟请求测试 |
| 196 | + |
| 197 | +编写单元测试 |
| 198 | + |
| 199 | +```java |
| 200 | +import org.junit.Test; |
| 201 | +import org.junit.runner.RunWith; |
| 202 | +import org.springframework.beans.factory.annotation.Autowired; |
| 203 | +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; |
| 204 | +import org.springframework.boot.test.context.SpringBootTest; |
| 205 | +import org.springframework.http.MediaType; |
| 206 | +import org.springframework.test.context.junit4.SpringRunner; |
| 207 | +import org.springframework.test.web.servlet.MockMvc; |
| 208 | +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; |
| 209 | + |
| 210 | +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; |
| 211 | +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; |
| 212 | + |
| 213 | +/** |
| 214 | + * 单元测试 |
| 215 | + */ |
| 216 | +@RunWith(SpringRunner.class) |
| 217 | +@SpringBootTest |
| 218 | +@AutoConfigureMockMvc |
| 219 | +public class HelloApplicationTests { |
| 220 | + |
| 221 | + @Autowired |
| 222 | + private MockMvc mvc; |
| 223 | + |
| 224 | + @Test |
| 225 | + public void contextLoads() throws Exception { |
| 226 | + mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) |
| 227 | + .andExpect(status().isOk()) |
| 228 | + .andExpect(content().string("Greetings from Spring Boot!")); |
| 229 | + } |
| 230 | + |
| 231 | +} |
| 232 | + |
| 233 | +``` |
| 234 | + |
| 235 | +关于上面代码的一些说明。 |
| 236 | + |
| 237 | +- **MockMvc** 允许我们方便的发送 HTTP 请求。 |
| 238 | +- **SpringBootTest** 方便的创建一个 Spring Boot 项目的测试程序。 |
| 239 | + |
| 240 | +运行没有任何异常说明程序测试通过。 |
| 241 | + |
| 242 | +### 6.2 Spring Boot 集成测试 |
| 243 | + |
| 244 | +```java |
| 245 | + |
| 246 | +import org.junit.Before; |
| 247 | +import org.junit.Test; |
| 248 | +import org.junit.runner.RunWith; |
| 249 | +import org.springframework.beans.factory.annotation.Autowired; |
| 250 | +import org.springframework.boot.test.context.SpringBootTest; |
| 251 | +import org.springframework.boot.test.web.client.TestRestTemplate; |
| 252 | +import org.springframework.boot.web.server.LocalServerPort; |
| 253 | +import org.springframework.http.ResponseEntity; |
| 254 | +import org.springframework.test.context.junit4.SpringRunner; |
| 255 | + |
| 256 | +import java.net.URL; |
| 257 | + |
| 258 | +/** |
| 259 | + * <p> |
| 260 | + * 嵌入式服务器由随机端口启动webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT |
| 261 | + * 并且在运行时发现实际端口@LocalServerPort |
| 262 | + * |
| 263 | + * @Author niujinpeng |
| 264 | + * @Date 2018/12/4 15:02 |
| 265 | + */ |
| 266 | +@RunWith(SpringRunner.class) |
| 267 | +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) |
| 268 | +public class HelloApplicationTestBySpringBoot { |
| 269 | + |
| 270 | + @LocalServerPort |
| 271 | + private int port; |
| 272 | + |
| 273 | + private URL base; |
| 274 | + |
| 275 | + @Autowired |
| 276 | + private TestRestTemplate template; |
| 277 | + |
| 278 | + @Before |
| 279 | + public void setup() throws Exception { |
| 280 | + this.base = new URL("http://localhost:" + port + "/"); |
| 281 | + } |
| 282 | + |
| 283 | + @Test |
| 284 | + public void getHello() throws Exception { |
| 285 | + ResponseEntity<String> response = template.getForEntity(base.toString(), String.class); |
| 286 | + assert (response.getBody().equals("Greetings from Spring Boot!")); |
| 287 | + } |
| 288 | + |
| 289 | +} |
| 290 | + |
| 291 | +``` |
| 292 | + |
| 293 | +嵌入式服务器由随机端口启动 `webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT` |
| 294 | + |
| 295 | +并且在运行时使用注解 `@LocalServerPort` 发现实际端口。 |
| 296 | + |
| 297 | +运行测试类通过输出。 |
| 298 | + |
| 299 | +```log |
| 300 | +2018-12-06 22:28:01.914 INFO 14320 --- [o-auto-1-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' |
| 301 | +2018-12-06 22:28:01.914 INFO 14320 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' |
| 302 | +2018-12-06 22:28:01.937 INFO 14320 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 23 ms |
| 303 | +``` |
| 304 | + |
| 305 | +文章代码已经上传到 GitHub [Spring Boot 入门案例](https://github.com/niumoo/springboot/tree/master/springboot-hello)。 |
0 commit comments