您的位置:首页 > 编程语言 > Java开发

spring-boot restful接口学习(1)

2016-12-31 23:36 295 查看
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")
@RestController
public 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请求,获取返回信息

@SpringBootApplication
public 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
###port
server:
  port: 7101

配置完成后,在idea中设置启动参数



最后点击运行

3、测试

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

效果浏览



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

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

备注

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

key: value

value与冒号之间要有一个空格,否则会出现报错
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring-boot restful接