Spring Boot 构建 Restful API 和测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lzx_2011/article/details/72810879

创建工程时已经选择了 web 模块,所以可以使用 springmvc。

注解介绍

@Controller:修饰class,用来创建处理http请求的对象

@RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。

controller 例子

这里使用restful controller ,返回的内容为 json


@RestController
@RequestMapping(value="/users")
public class MyRestController {

    @RequestMapping(value="/{user}", method= RequestMethod.GET)
    public User getUser(@PathVariable Long user) {
        // ...
        User user1 = new User();
        user1.setId(user);
        user1.setName("liu");
        user1.setAge(20);
        return user1;
    }

    @RequestMapping(value="/{user}", method=RequestMethod.DELETE)
    public User deleteUser(@PathVariable Long user) {
        // ...
        User user1 = new User();
        user1.setId(user);
        user1.setName("liu");
        return user1;
    }

}

单元测试

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyRestControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private MyRestController myRestController;

    @Test
    public void userTest() {

        User user1 = restTemplate.getForObject("/users/2", User.class);
        System.out.println(user1.toString());

        User user = this.myRestController.getUser(1L);
        System.out.println(user.toString());

    }
}

运行程序

启动 web 应用,执行命令

mvn spring-boot:run

在浏览器上输入 http://localhost:8080/users/1 可以看到返回结果

{"id":1,"name":"liu","age":20}

项目示例:https://github.com/lzx2011/springBootPractice

参考资料

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

猜你喜欢

转载自blog.csdn.net/lzx_2011/article/details/72810879