在您第1次接触和学习Spring框架的时候,是否由于其繁杂的配置而退却了?在你第n次使用Spring框架的时候,是否以为一堆反复黏贴的配置有一些厌烦?那么您就不妨来试试使用Spring Boot来让你更易上手,更简单快捷地构建Spring应用!java
Spring Boot让咱们的Spring应用变的更轻量化。好比:你能够仅仅依靠一个Java类来运行一个Spring引用。你也能够打包你的应用为jar并经过使用java -jar来运行你的Spring Web应用。web
Spring Boot的主要优势:spring
本章主要目标完成Spring Boot基础项目的构建,而且实现一个简单的Http请求处理,经过这个例子对Spring Boot有一个初步的了解,并体验其结构简单、开发快速的特性。浏览器
本文采用Java 1.8.0_73
、Spring Boot 1.3.2
调试经过。mvc
SPRING INITIALIZR
工具产生基础项目
http://start.spring.io/
Maven Project
、Spring Boot版本1.3.2
以及一些工程基本信息,可参考下图所示SPRING INITIALIZRapp
Generate Project
下载项目压缩包Maven
项目导入,以IntelliJ IDEA 14
为例:
File
–>New
–>Project from Existing Sources...
OK
Import project from external model
并选择Maven
,点击Next
到底为止。Java SDK
的时候请选择Java 7
以上的版本项目结构框架
经过上面步骤完成了基础项目的建立,如上图所示,Spring Boot的基础结构共三个文件(具体路径根据用户生成项目时填写的Group全部差别):函数
src/main/java
下的程序入口:Chapter1Application
src/main/resources
下的配置文件:application.properties
src/test/
下的测试入口:Chapter1ApplicationTests
生成的Chapter1Application
和Chapter1ApplicationTests
类均可以直接运行来启动当前建立的项目,因为目前该项目未配合任何数据访问或Web模块,程序会在加载完Spring以后结束运行。spring-boot
当前的pom.xml
内容以下,仅引入了两个模块:工具
spring-boot-starter
:核心模块,包括自动配置支持、日志和YAMLspring-boot-starter-test
:测试模块,包括JUnit、Hamcrest、Mockito<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
引入Web模块,需添加spring-boot-starter-web
模块:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
package
命名为com.didispace.web
(根据实际状况修改)HelloController
类,内容以下@RestController public class HelloController { @RequestMapping("/hello") public String index() { return "Hello World"; } }
http://localhost:8080/hello
,能够看到页面输出Hello World
编写单元测试用例
打开的src/test/
下的测试入口Chapter1ApplicationTests
类。下面编写一个简单的单元测试来模拟http请求,具体以下:
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MockServletContext.class) @WebAppConfiguration public class Chapter1ApplicationTests { private MockMvc mvc; @Before public void setUp() throws Exception { mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build(); } @Test public void getHello() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("Hello World"))); } }
使用MockServletContext
来构建一个空的WebApplicationContext
,这样咱们建立的HelloController
就能够在@Before
函数中建立并传递到MockMvcBuilders.standaloneSetup()
函数中。
status
、content
、equalTo
函数可用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;
至此已完成目标,经过Maven构建了一个空白Spring Boot项目,再经过引入web模块实现了一个简单的请求处理。