Using Swagger2 to build restful APIs in Spring MVC

Source: Internet
Author: User

1.maven Dependency

<!--building RESTful APIs--<dependency>    <groupId>io.springfox</ groupId>    <artifactid>springfox-swagger2</artifactid>    < version>2.6.0</version></dependency><Dependency >    <groupId>io.springfox</groupId>    <artifactid> springfox-swagger-ui</Artifactid>    <version>2.6.0</version ></Dependency>
2.Swagger configuration file
 PackageCom.custom.web.swagger;ImportCom.google.common.base.Predicate;ImportOrg.springframework.context.annotation.Bean;ImportOrg.springframework.context.annotation.ComponentScan;ImportOrg.springframework.context.annotation.Configuration;ImportORG.SPRINGFRAMEWORK.WEB.SERVLET.CONFIG.ANNOTATION.ENABLEWEBMVC;ImportOrg.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;ImportSpringfox.documentation.builders.ApiInfoBuilder;ImportSpringfox.documentation.builders.PathSelectors;ImportSpringfox.documentation.builders.RequestHandlerSelectors;ImportSpringfox.documentation.service.ApiInfo;ImportSpringfox.documentation.service.ApiKey;ImportSpringfox.documentation.service.AuthorizationScope;ImportSpringfox.documentation.service.SecurityReference;ImportSpringfox.documentation.spi.DocumentationType;ImportSpringfox.documentation.spi.service.contexts.SecurityContext;ImportSpringfox.documentation.spring.web.plugins.Docket;ImportSpringfox.documentation.swagger2.annotations.EnableSwagger2;ImportJava.util.List;Import Staticcom.google.common.base.Predicates.or;Import StaticCom.google.common.collect.Lists.newArrayList;Import StaticSpringfox.documentation.builders.PathSelectors.regex; @Configuration//configure annotations to automatically load some environment variable information in this class context@EnableSwagger2//Make Swagger2 effective@EnableWebMvc @componentscan (basepackages = {"Com.custom.web"})//package path that needs to be scannedPublic classSwaggerconfigextendsWebmvcconfigurationsupport {@Bean PublicDocket Swaggerspringmvcplugin () {return newDocket (Documentationtype.swagger_2). Apiinfo (Apiinfo ()). GroupName ("Business-api"). Select ()//Select those paths and APIs to generate document. APIs (Requesthandlerselectors.basepackage ("Com.custom.web"). Paths (Paths ())//.apis (Requesthandlerselectors.any ())//monitoring of all APIs//.paths (Pathselectors.any ())//monitoring of all paths. Build (). Securityschemes (Securityschemes ()). Securitycontexts (Securitycontexts ()); }PrivatePredicate<string> paths () {returnor (Regex ("/person.*")); }PrivateList<apikey> Securityschemes () {returnNewarraylist (NewApiKey ("ClientId","Client ID","Header"),NewApiKey ("Clientsecret","Client secret key","Header"),NewApiKey ("Accesstoken","Client Access Identity","Header")); }PrivateList<securitycontext> securitycontexts () {returnNewarraylist (Securitycontext.builder (). Securityreferences (Defaultauth ()) . Forpaths (Pathselectors.regex ("/*.*")). Build ()); } list<securityreference> Defaultauth () {Authorizationscope Authorizationscope =NewAuthorizationscope ("Global","Accesseverything"); authorizationscope[] Authorizationscopes =NewAUTHORIZATIONSCOPE[1]; Authorizationscopes[0] = Authorizationscope;returnNewarraylist (NewSecurityreference ("ClientId", Authorizationscopes),NewSecurityreference ("Clientsecret", Authorizationscopes),NewSecurityreference ("Accesstoken", authorizationscopes)); }PrivateApiinfo Apiinfo () {return newApiinfobuilder (). Title ("Using Swagger2 to build restful APIs in Spring"). Termsofserviceurl ("http://blog.csdn.net/yangshijin1988"). Description ("This API provides interface calls"). License ("License Version 2.0"). Licenseurl ("http://blog.csdn.net/yangshijin1988"). Version ("2.0"). build (); }}
Add API documentation using annotations in 3.Controller
 PackageCom.custom.web.index.controller;ImportCom.custom.web.index.entity.Person;ImportIo.swagger.annotations.Api;ImportIo.swagger.annotations.ApiOperation;ImportOrg.springframework.http.MediaType;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.bind.annotation.ResponseBody;/*** Created by Administrator on 2017/4/8. */@Controller @requestmapping ("/person") @Api (tags="Personal Business")Public classPersonController {@RequestMapping (value="/getperson", method= Requestmethod.GET) @ApiOperation (HttpMethod ="GET", value ="Personal Information", produces = mediatype.Application_json_value) Public@ResponseBody person Getpersons () {Person person =NewPerson (); Person.setfirstname ("FName"); Person.setlastname ("LName");        Person.setage (37); Person.setdeptname ("Dept");returnPerson }}
4.web.xml Configuration Instructions
 <  servlet  > <  servlet-name  >dispatcher</ servlet-name< /strong>> <  servlet-class  >org.springframework.web.servlet.dispatcherservlet</  Servlet-class  > <  init-param  > <  param-name  >contex tconfiglocation</ param-name  > <  param-value  >classpath*:/ spring-mvc.xml</ param-value  > </ init-param  > <  Load-on-startup  >1</ load-on-startup  ></ servlet  ><  servlet-mapping  > <  servlet-name  >dispatcher</ servlet-name  > <  url-pattern  >*.do</ url-pattern  ></ Servlet-mapping ; 
<servlet-mapping>    <servlet-name>dispatcher</servlet-name>    <url-pattern>/v2/api-docs</url-pattern></servlet-mapping>
Description: SPRINGMVC Front Controller scan path added "/v2/api-docs" for scanning swagger /v2/api-docs, otherwise /v2/api-docs cannot take effect.   5.spring-mvc.xml increased automatic scanning swagger
<!--use Swagger Restful API documentation, add this note--<MVC/><mvc: Annotation-driven/>
or <MVCLocationmapping= "swagger-ui.html"/><  MVCLocation Mapping= "/webjars/**"/>
6. Effects show restful API Access path: http://ip:port/{context-path}/swagger-ui.html   7. Using the Swagger UI templateCan be downloaded from swagger website. Address: Https://github.com/swagger-api/swagger-ui. After the download is complete, place the template under the Dist directory under Swagger-ui into the project, such as create a new Swagger Swagger-ui template under Project Web-app. Configure automatic filtering of Swagger folders in Spring-mvc.
<MVCmappinglocationcache-period/ >
Change the URL of the index.html or swagger-ui.html file js to URL = "/v2/api-docs?group=business-api";

Using Swagger2 to build restful APIs in Spring MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.