http://start.spring.io/
- src/main/java 程序开发以及主程序入口 - src/main/resources 配置文件 - src/test/java 测试程序
Spring Boot 建议的目录规划以下:java
com +- easy +- helloworld +- HelloworldApplication.java | +- model | +- User.java | +- UserRepository.java | +- service | +- UserService.java | +- controller | +- UserController.java |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> 也能够在建立项目的时候直接选择web依赖 spring-boot-starter :核心模块,包括自动配置支持、日志和 YAML,若是引入了 spring-boot-starter-web web 模块能够去掉此配置,由于 spring-boot-starter-web 自动依赖了 spring-boot-starter。 spring-boot-starter-test :测试模块,包括 JUnit、Hamcrest、Mockito
Controller 内容:git
@RestController public class HelloWorldController { @RequestMapping("/hello") public String index() { return "Hello World"; } } @RestController默认都只提供Rest风格接口返回值,针对不须要返回页面的Controller都采用RestController进行注解
打开浏览器访问 http://localhost:8080/hello,就能够看到效果了,是否是很是简单快速!
打开的src/test/下的测试入口,编写简单的 http 请求来测试;使用 mockmvc 进行,代码以下。github
package com.easy.helloworld; import com.easy.helloworld.controller.HelloWorldController; 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.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 public class HelloTests { private MockMvc mvc; @Before public void setUp() throws Exception { mvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).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"))); } }
MockMvc使用参考官网,这里不作介绍web
<!--开发环境热部署插件--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>
使用 Spring Boot 能够很是方便、快速搭建项目,使咱们不用关心框架之间的兼容性,适用版本等各类问题,咱们想使用任何东西,仅仅添加一个配置就能够,因此使用 Spring Boot 很是适合构建微服务。spring
示例代码-github浏览器