欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解使用Spring Boot开发Restful程序

程序员文章站 2024-02-20 23:42:40
一、简介 spring boot是由pivotal团队提供的全新框架,其设计目的是用来简化新spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,...

一、简介

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配置。其主要目标如下:

  1. 为所有的spring开发工作提供一个更快、更广泛的入门经验。
  2. 开箱即用,你也可以通过修改默认值来快速满足你的项目的需求。
  3. 提供了一系列大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标,健康检测、外部配置等。

spring boot官网:

二、开发环境准备

ide:intellij idea

官网地址:

jdk:1.8

maven

数据库:mysql

我将以一个用户积分系统为例,开发一个restful风格的服务端

三、第一个restful程序

1.新建一个普通maven工程

详解使用Spring Boot开发Restful程序

详解使用Spring Boot开发Restful程序

详解使用Spring Boot开发Restful程序

详解使用Spring Boot开发Restful程序

创建项目完成后目录结构如下图所示

详解使用Spring Boot开发Restful程序

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;
 }}

  1. 关键字@restcontroller代表这个类是用restful风格来访问的,如果是普通的web页面访问跳转时,我们通常会使用@controller
  2. value = "/users/{username}" 代表访问的url是"http://host:port/users/实际的用户名"
  3. method = requestmethod.get 代表这个http请求必须是以get方式访问
  4. consumes="application/json" 代表数据传输格式是json
  5. @pathvariable将某个动态参数放到url请求路径中
  6. @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插件来模拟请求

详解使用Spring Boot开发Restful程序

在发起请求前,请注意需要在headers中设置content-type为application/json

到此一个基本的restful风格的服务端就已经完成了,全部编码时间不会超过5分钟!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。