spring-boot restful接口学习(1)

来源:互联网 发布:手写图片识别软件 编辑:程序博客网 时间:2024/04/30 09:47

1、前言

因为工作需要,开始写后台服务的接口,使用的框架是spring-boot。关于微服务的好处、架构,产生的渊源,度娘上一堆文章,官网上也有很多描述,这里不再赘述。这里只是准备梳理一下用spring-boot做微服务接口的相关知识。从最基本的开始,一点点记录自己的学习过程。也算是在总结的过程加深自己对这方面技术的认识。

2、第一个hello接口

这个接口是spring-boot官网上的例子。具体的实现可以查看官网,或者看我放在github上的测试代码

git地址:https://github.com/learnerfan/spring-boot-restful.git

代码结构


创建controller,通过

 @RequestMapping
来设置访问路径

@RequestMapping("/api/v1.0/greeting")@RestControllerpublic class GreetingController {    @RequestMapping(value = "/hello",method = RequestMethod.GET)    @ApiOperation(value = "问候接口",notes = "hello")    public JSONObject greet(@RequestParam()String name){        JSONObject response = new JSONObject();        response.put("message","hello"+"   "+name);        return response;    }}
该接口的主要功能是发送get请求,获取返回信息

@SpringBootApplicationpublic class LearnApp extends WebMvcConfigurerAdapter {    public static void main(String[] args){        SpringApplication.run(LearnApp.class,args);    }}

#spring.jackson.date-format=yyyy-MM-dd'T'HH:mm:ss.SSSZ###portserver:  port: 7101
配置完成后,在idea中设置启动参数


最后点击运行

3、测试

打开浏览器,访问localhost:7101/api/v1.0/greeting/hello?name="世界"

效果浏览


5、这知识一个简单的例子,实现的逻辑也不复杂,spring-boot写接口的时候完全可以遵循mvc模型

一般会设置dao、service、controller三层,用于数据库访问,组装数据,处理不同资源路径的请求。更多的内容后续会继续介绍

备注

在写yml配置文件的时候需要注意

key: value

value与冒号之间要有一个空格,否则会出现报错

1 0
原创粉丝点击