三、Spring Boot构建RESTful API

来源:互联网 发布:android js语言 编辑:程序博客网 时间:2024/05/31 19:06

定义实体类

package com.lf.entity;/** * Created by LF on 2017/4/11. */public class User {    private Long id;    private String name;    private Integer age;    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }}

RestfulController

package com.lf.web;import com.lf.entity.User;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;/** * Created by LF on 2017/4/11. */@RestControllerpublic class RestfulController {    @RequestMapping(value = "/user/{code}", method = RequestMethod.GET)    public User getUser(@PathVariable String code) {        //根据code查询        return new User();    }    @RequestMapping(value = "/user", method = RequestMethod.POST)    public void createUser(User user) {        //数据库添加    }    @RequestMapping(value = "/user/{code}", method = RequestMethod.PUT)    public void updateUser(@PathVariable String code, User user) {        //根据code更新用户    }    @RequestMapping(value = "/user/{code}", method = RequestMethod.DELETE)    public void deletUser(@PathVariable String code) {        //根据code删除一个用户    }}
package com.lf;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

@RestController

Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代.

至此,我们通过引入web模块(没有做其他的任何配置),就可以轻松利用Spring MVC的功能,以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。其中同时介绍了Spring MVC中最为常用的几个核心注

0 0