入门
本文适用于不熟悉spring的小白。博主本人也是初次接触。有错误的请指导~
参考http://blog.didispace.com/ 这位博主的分享,会更改他一些代码使适用于springboot 1.5.10
构建项目
系统要求:
- 使用 Intellij IDEA, java 1.8
构建项目:
全部使用默认设置即可
文件结构:
- .idea/.mvn暂时无用。不需要更改
- .src 主要的源代码都是在这个文件夹下分为main与test两个子文件夹,都是自动生成
- main/java:所有源文件存放点
- main/resource: 该子文件夹下有application.properties,是用来配置一些参数的。比如数据库的账户密码等。
- test/java:测试用的源文件。可以通过编写测试用的代码来直接调试(使用@Test),比如在代码中写要调试的函数。传进去的参数等等。若结果为0则顺利通过,-1则有错误。通过Log等工具来看调试信息。
- pom.xml:maven的配置文件。发现通过maven添加依赖包很方便。不需要自己下那么多jar包,而且IDEA可以选择生成maven项目。也不需要自己配置maven。如要用springboot项目。则添加下面两个依赖
<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>
处理简单的http请求并进行测试
先写请求处理
新建一个类HelloController,使用注解@RestController与@RequestMapping。@RestController与@Controller的区别是比较简单,不需要添加模板,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。两者的功能就是处理http请求。而@RequestMapping的作用则是对url进行匹配,若加在方法前则只作用于方法。加在类前则作用与整个类里面的方法。如
@RestController
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(value="/1", method="RequestMethod.GET")
public String one(){
return "one";//遇到localhost/hello/1 则返回"one"
}
@RequestMapping(value="/2", method="RequestMethod.GET")
public String two(){
return "two";//遇到localhost/hello/2 则返回"two"
}
}
简单测试
测试是在test/java下的class。使用到注解@Before, @Test。
@Before是每个方法执行前都会执行一次的方法,用于初始化。
@Test则是我们测试用的方法。
使用MockMvc来进行测试。
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 SpringbootApplicationTests {
private MockMvc mvc;
@Before
public void setUp() throws Exception{
mvc= MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test
public void contextLoads() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello/1")//表示执行的是get
.accept(MediaType.APPLICATION_JSON))//接受的数据格式
.andExpect(status().isOk())//期待的回应
.andExpect(content().string(equalTo("one")));
}
}
文件结构
根目录假设为root
- 应用主类Application.java放在根目录下
- Entity&Repository放在root.domain下
- 逻辑层(service)放在root.service下
- Web层(web)放在root.web下,这里的HelloController就放在web层下