使用Spring Boot开发Restful程序
一、简介
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
多年以来,Spring IO平台饱受非议的一点就是大量的XML配置以及复杂的依赖管理。在去年的SpringOne 2GX会议上,Pivotal的CTO Adrian Colyer回应了这些批评,并且特别提到该平台将来的目标之一就是实现免XML配置的开发体验。Boot所实现的功能超出了这个任务的描述,开发人员不仅不再需要编写XML,而且在一些场景中甚至不需要编写繁琐的import语句。在对外公开的beta版本刚刚发布之时,Boot描述了如何使用该框架在140个字符内实现可运行的web应用,从而获得了极大的关注度,该样例发表在tweet上。
Spring Boot不生成代码,且完全不需要XML配置。其主要目标如下:
- 为所有的Spring开发工作提供一个更快、更广泛的入门经验。
- 开箱即用,你也可以通过修改默认值来快速满足你的项目的需求。
- 提供了一系列大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标,健康检测、外部配置等。
Spring Boot官网: http://projects.spring.io/spring-boot/
二、开发环境准备
- IDE:IntelliJ IDEA
官网地址:https://www.jetbrains.com/idea/download/ - JDK:1.8
- Maven
- 数据库:MySQL
我将以一个用户积分系统为例,开发一个Restful风格的服务端
三、第一个Restful程序
1.新建一个普通Maven工程
创建项目完成后目录结构如下图所示
2.在POM文件中加入对Spring-Boot的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.bluecoffee</groupId><artifactId>mapp</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.4.1.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
3.新建一个RestController来接收客户端的请求,我们来模拟一个登录请求
package com.yepit.mapp.rest;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;/*** Created by qianlong on 16/7/20.*/
@RestController
public class UserController{@RequestMapping(value = "/users/{username}",method = RequestMethod.GET,consumes="application/json")public String getUser(@PathVariable String username, @RequestParam String pwd){return "Welcome,"+username;}}
- 关键字@RestController代表这个类是用Restful风格来访问的,如果是普通的WEB页面访问跳转时,我们通常会使用@Controller
- value = "/users/{username}" 代表访问的URL是"http://host:PORT/users/实际的用户名"
- method = RequestMethod.GET 代表这个HTTP请求必须是以GET方式访问
- consumes="application/json" 代表数据传输格式是json
- @PathVariable将某个动态参数放到URL请求路径中
- @RequestParam指定了请求参数名称
4.新建启动Restful服务端的启动类
package com.yepit.mapp;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** Created by qianlong on 16/7/20.*/
@SpringBootApplication
public class MappRunApplication{public static void main(String[] args){SpringApplication.run(MappRunApplication.class, args);}
}
5.执行MappRunApplication的Main方法启动Restful服务,可以看到控制台有如下输出
. ____ _ __ _ _/\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\
( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\\\\/ ___)| |_)| | | | | || (_| | ) ) ) )' |____| .__|_| |_|_| |_\\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v1.3.3.RELEASE)2016-07-20 16:49:43.334 INFO 2106 --- [ main] com.yepit.mapp.MappRunApplication : Starting MappRunApplication on bogon with PID 2106 (/Users/qianlong/workspace/spring-boot-samples/target/classes started by qianlong in /Users/qianlong/workspace/spring-boot-samples)
2016-07-20 16:49:43.338 INFO 2106 --- [ main] com.yepit.mapp.MappRunApplication : No active profile set, falling back to default profiles: default
2016-07-20 16:49:43.557 INFO 2106 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@543e710e: startup date [Wed Jul 20 16:49:43 CST 2016]; root of context hierarchy
2016-07-20 16:49:44.127 INFO 2106 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2016-07-20 16:49:44.658 INFO 2106 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-07-20 16:49:44.672 INFO 2106 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-07-20 16:49:44.673 INFO 2106 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.32
2016-07-20 16:49:44.759 INFO 2106 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-07-20 16:49:44.759 INFO 2106 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1207 ms
2016-07-20 16:49:44.972 INFO 2106 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-07-20 16:49:44.977 INFO 2106 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-07-20 16:49:44.978 INFO 2106 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-07-20 16:49:44.978 INFO 2106 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-07-20 16:49:44.978 INFO 2106 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-07-20 16:49:45.184 INFO 2106 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@543e710e: startup date [Wed Jul 20 16:49:43 CST 2016]; root of context hierarchy
2016-07-20 16:49:45.251 INFO 2106 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users],methods=[GET],consumes=[application/json]}" onto public java.lang.String com.yepit.mapp.rest.UserController.getUser(java.lang.String,java.lang.String)
2016-07-20 16:49:45.253 INFO 2106 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-07-20 16:49:45.254 INFO 2106 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-07-20 16:49:45.275 INFO 2106 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-07-20 16:49:45.275 INFO 2106 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-07-20 16:49:45.306 INFO 2106 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-07-20 16:49:45.380 INFO 2106 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-07-20 16:49:45.462 INFO 2106 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-07-20 16:49:45.467 INFO 2106 --- [ main] com.yepit.mapp.MappRunApplication : Started MappRunApplication in 2.573 seconds (JVM running for 3.187)
我们可以看到服务器是Tomcat,端口为8080
6.验证
推荐大家使用Google的Postman插件来模拟请求
在发起请求前,请注意需要在Headers中设置Content-Type为application/json
到此一个基本的Restful风格的服务端就已经完成了,全部编码时间不会超过5分钟!
使用Spring Boot开发Restful程序相关推荐
- 学习笔记-Spring Boot 开发 RESTful Web API(一)
题记: 本篇是Spring Boot 开发学习系列中基础知识学习的一部分,为 RESTful Web API 相关基础知识,为实践操作奠定理论基础. REST不是一个标准,而是一种软件应用架构风格.基 ...
- 使用 spring boot 开发通用程序
2019独角兽企业重金招聘Python工程师标准>>> tag: spring 学习笔记 date: 2018-03 spring 是什么?spring 核心是应用组件容器,管理组件 ...
- springboot thymeleaf配置_【程序源代码】Spring Boot 开发笔记web开发实战1
关键字:<Spring Boot 开发笔记>系列文章 各位亲爱的小伙伴:大家好! <Spring Boot 开发笔记>系列文章 这套笔记和源码是我自己在学习springboot ...
- 真的简单,单手用Spring Boot 开发一个微信小程序
前言 嗨,大家好,现在微信使用的用户很多,作为开发人员也可以建立一个自己的微信小程序,本期与大家分享一下作者建立微信小程序的开发流程. 申请 百度搜索微信公众号平台,然后扫码登录注册一个微信公 ...
- Spring Boot 构建RESTful Web服务
Spring Boot 构建RESTful Web服务 本指南将引导您完成使用Spring 创建" Hello World" RESTful Web服务的过程. 你会建立什么 您将 ...
- 从零搭建一个 Spring Boot 开发环境!Spring Boot+Mybatis+Swagger2 环境搭建
从零搭建一个 Spring Boot 开发环境!Spring Boot+Mybatis+Swagger2 环境搭建 本文简介 为什么使用Spring Boot 搭建怎样一个环境 开发环境 导入快速启动 ...
- spring boot 开发soap webservice
介绍 spring boot web模块提供了RestController实现restful,第一次看到这个名字的时候以为还有SoapController,很可惜没有,对于soap webservic ...
- 分布式 Spring Cloud 基于 Spring Boot 开发一整套
Spring Boot的工程包括: - Spring IO Platform:用于版本化应用程序的企业级分发. - Spring Framework:用于事务管理.依赖注入.数据访问.消息传递和W ...
- Spring Boot开发介绍
Spring Boot开发介绍 Spring Boot介绍 安装Spring Boot插件 创建Spring Boot项目 Idea 创建Spring Boot项目失败 解决方法1-更换为aliyun ...
最新文章
- iOS 中 load 和 initialize的实现顺序
- 腾讯AI单挑碾压王者荣耀职业玩家:人类15场只能赢1局,坚持不到8分钟 | “绝悟”技术细节披露...
- OO_Unit2_多线程电梯
- php7过滤,PHP7过滤unserialize()
- html:(35):缩进和行高
- DreamWeaver使用技巧学习心得
- 鱼眼图像畸变校正--透视变换
- 【李宏毅2020 ML/DL】P66 Self-supervised Learning
- python2中的print语句可以不用小括号。_Python 2.7终结于7个月后,这是你需要了解的3.X炫酷新特性...
- Mysql删除数据报外键约束解决方法
- php养老院管理系统论文,养老院一卡通管理
- 【深度】“考上北大,我们也和那几亿的农民工人互为镜像”
- luci编程 openwrt_【玩转开源】BananaPi R2 —— 第四篇 Openwrt Luci 初探
- jmeter里看java的log,jmeter中java协议请求
- 安卓逆向学习笔记(一)
- 软件平台平台物联网操作系统系列文章之-软件平台的力量
- matlab院校,MATLAB要来了?!
- android 辅助功能 长按发语音,简单模拟微信长按语音发送效果
- 搜狐号第三届创作者大会落幕:胡锡进管清友谭飞雷建平论道
- driver failed programming external connectivity on endpoint
热门文章
- 1001 A+B Format (20分)——12行代码AC
- excel 电阻并联计算_电阻器的构成及取代原则
- Mysql数据库(八)——mysql高阶语句(中)
- python列表反向取值_Python列表的反向遍历,python,逆序
- 数据流程图顶层一层二层_只需三个公式,三阶魔方超简单入门图文教程5:完全复原第二层...
- 2020idea创建web项目_Spring Boot + Mybatis 多模块(module)项目的完整搭建教程
- jmeter难吗_Jmeter集成Jira提交缺陷
- ida导入jni头文件_IDA导入Jni.h
- python创建excel_python创建Excel文件数据的方法
- java httpclient教程_HttpClient4.5.2 HTTP协议的请求和执行