springBoot环境搭建成功,我们来写一个Hello world项目吧!
1.编写项目构建信息
gradle构建工具跟maven还是有区别,最明显的区别就是依赖包定义格式差别很大。
build.gradle配置文件:
2.自定义存储仓库,加速构建
build.gradle repositories配置信息,可参考文章:https://blog.csdn.net/chengchengjava/article/details/79825090
3.编写程序代码及测试用例
后台编码:
(1)在main方法在同级别包下创建HelloWorldController控制器
(2)HelloWorld控制器代码
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello world";
}
}
重点看一下:@RestController注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
* @since 4.0.1
*/
@AliasFor(annotation = Controller.class)
String value() default "";
}
@RequestMapping 请求映射注释
@GetMapping 发送get请求
@PostMapping 发送post请求
大家可以参看源码去理解。来看一下修改之后的结果:
测试用例:
(1)test目录下,创建测试用例HelloControllerTests
(2)测试用例代码
@RunWith(SpringRunner.class)
@SpringBootTest(classes=HelloControllerTests.class)
@AutoConfigureMockMvc
public class HelloControllerTests {
@Autowired
private MockMvc mockMvc;
@Test
public void testHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)).andReturn();
}
}
重点关注一下:@SpringBootTest注解
4.了解gradle/wrapper
初始化的springBoot项目有个gardle文件夹,里面有个wrapper目录。该目录的作用:团队之间合作中,可以统一gradle构建的版本,具体可参考gradle-wrapper.properties配置文件。