java Spring boot的最简单最详细的入门案例
2017-07-09 本文已影响0人
每天学点编程
Spring Boot使得Spring应用变得更轻量化。
Spring Boot的主要优点:
- 为所有Spring开发者更快的入门
- 开箱即用,提供各种默认配置来简化项目配置
- 内嵌式容器简化Web项目开发
- 没有冗余代码生成和XML配置的要求
使用IDEA来创建Spring boot项目
选择Spring Initializr:

输入项目的各种信息:

可以根据需要选择依赖:

项目的名称和位置:

项目结构

一个很典型的maven项目结果而已。
可以直接运行DemoApplication
和DemoApplicationTests
,但是在加载完Spring之后就会结束运行。
引入Web模块
pom.xml
引入了两个模块:
spring-boot-starter:核心模块,包括自动配置支持、日志和YAML
spring-boot-starter-test:测试模块,包括JUnit、Hamcrest、Mockito

引入Web模块,需添加spring-boot-starter-web
模块:

同时可以删除spring-boot-starter。
HelloWorld例子

启动程序,打开浏览器访问http://localhost:8080/hello:

编写单元测试

使用MockServletContext
来构建一个空的WebApplicationContext
,这样我们创建的HelloController
就可以在@Before
函数中创建并传递到MockMvcBuilders.standaloneSetup()
函数中。