SpringMVC+Swagger详细整合
发布时间:2020-12-15 07:10:18 所属栏目:Java 来源:网络整理
导读:一、新建maven工程导入正确的pom文件 还是那句话,包导入正确就成功了80%。剩下的20%慢慢攻克吧。 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
一、新建maven工程导入正确的pom文件 还是那句话,包导入正确就成功了80%。剩下的20%慢慢攻克吧。 <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.apidoc.demotest</groupId>
<artifactId>apidoc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>4.1.7.RELEASE</spring.version>
<version.jackson>2.4.4</version.jackson>
<swagger.version>2.2.2</swagger.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${version.jackson}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${version.jackson}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${version.jackson}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
<version>3.1.0</version>
</dependency>
<!--petstore是官方的一个demo,加入此依赖是为了稍后参考接口描述的编写 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-petstore</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.logback-extensions</groupId>
<artifactId>logback-ext-spring</artifactId>
<version>0.1.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
?二、建包并创建对应java文件 (1) package com.apidoc.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
@Configuration
@EnableSwagger
@EnableWebMvc
public class SwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;
/**
* Required to autowire SpringSwaggerConfig
*/
@Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
/**
* Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc
* framework - allowing for multiple swagger groups i.e. same code base
* multiple swagger resource listings.
*/
@Bean
public SwaggerSpringMvcPlugin customImplementation() {
// 暂时不用过滤
/*return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).includePatterns(".*pet.*");*/
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo(
"My Apps API Title","My Apps API Description","My Apps API terms of service","My Apps API Contact Email","My Apps API Licence Type","My Apps API License URL"
);
return apiInfo;
}
}
? ? ?(2) package com.apidoc.model;
public class User{
private String Id;
String Name;
Integer Age;
public String getId() {
return Id;
}
void setId(String id) {
Id = id;
}
String getName() {
Name;
}
setName(String name) {
Name = name;
}
Integer getAge() {
Age;
}
setAge(Integer age) {
Age = age;
}
}
(3) com.apidoc.webservice;
import javax.servlet.http.HttpServletRequest;
org.springframework.stereotype.Controller;
org.springframework.web.bind.annotation.RequestMapping;
org.springframework.web.bind.annotation.RequestMethod;
org.springframework.web.bind.annotation.RequestParam;
org.springframework.web.bind.annotation.ResponseBody;
com.apidoc.model.User;
com.wordnik.swagger.annotations.ApiOperation;
com.wordnik.swagger.annotations.ApiParam;
net.sf.json.JSONObject;
/**
* @moudle: WebServiceForCSS
* @version:v1.0
* @Description: TODO
* @author: xukai
* @date: 2016年12月1日 下午5:37:30
*
*/
@Controller
WebServiceForCSS {
@ResponseBody
@RequestMapping(value = "getUserById",method = RequestMethod.GET,produces = {"application/json; charset=utf-8","application/xml"})
@ApiOperation(value = "通过ID查询USER信息",httpMethod = "POST",notes = "暂无")
String getUserById(
@ApiParam(required = true,name = "id",value = "ID")
@RequestParam(value = "id") String id,HttpServletRequest request) {
User user = new User();
user.setId(id);
user.setName("测试人员");
user.setAge(25);
JSONObject object = JSONObject.fromObject(user);
object.toString();
}
}
? 三、根据web.xml建立spring文件夹以及springmvc和spring相关的xml文件 <?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>SwaggerDemo</display-name>
<!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/application-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
- Servlet that dispatches request to registered handlers (Controller implementations).
-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.ico</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.xls</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.doc</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
<!-- 字体相关 开始 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.eot</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.svg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.ttf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.woff</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.woff2</url-pattern>
</servlet-mapping>
<!-- 字体相关 结束 -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
? ? 在上述的基础上开始建立xml配置文件 (1) <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven /> <!-- mvc-config.xml中的可以去掉 -->
<context:component-scan base-package="com.apidoc"/>
<bean class="com.apidoc.config.SwaggerConfig"/>
</beans>
? ? ? (2) <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Uncomment and your base-package here:
<context:component-scan
base-package="org.springframework.samples.web"/> -->
bean ="org.springframework.web.servlet.view.InternalResourceViewResolver">
Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
property name="prefix" value="/WEB-INF/view/"/>
="suffix"=".jsp"/>
</bean>
beans>
? 四、进入swagger相关的github网站下载的swagger版本 网址如下: https://github.com/swagger-api/swagger-ui 下载成功后,将dist目录拷贝到webapp目录下 拷贝成功后,将拷贝的dist目录下的index.html文件中的url修改为自己项目文档路径 <!-- HTML for static distribution bundle build -->
? ?五、新建一个json文件,配置如下 {
"swagger": "2.0","info": {
"description": "swagger-ui的汉化版本","version": "1.0.0","title": "汉化版Swagger-UI","termsOfService": "http://swagger.io/terms/","contact": {
"email": "helei5200@126.com"
},"license": {
"name": "Apache 2.0","url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},"host": "petstore.swagger.io","basePath": "/v2","tags": [
{
"name": "pet","description": "有关你宠物的所有事情!","externalDocs": {
"description": "Find out more","url": "http://swagger.io"
}
},{
"name": "store","description": "访问宠物商店订单!"
},{
"name": "user","description": "操作用户相关!","externalDocs": {
"description": "Find out more about our store","url": "http://swagger.io"
}
}
],"schemes": [
"http"
],"paths": {
"/pet": {
"post": {
"tags": [
"pet"
],"summary": "添加一个新宠物到商店!","description": "","author": "helei 更新于 2015/06/17 19:56","operationId": "addUser","consumes": [
"application/json","application/xml"
],"produces": [
"application/xml","application/json"
],"parameters": [
{
"in": "body","name": "body","description": "Pet object that needs to be added to the store","required": true,"schema": {
"$ref": "#/definitions/Pet"
}
}
],"responses": {
"405": {
"description": "Invalid input"
}
},"security": [
{
"petstore_auth": [
"write:pets","read:pets"
]
}
]
},"put": {
"tags": [
"pet"
],"summary": "更新存在的宠物信息","operationId": "updatePet","responses": {
"400": {
"description": "Invalid ID supplied"
},"404": {
"description": "Pet not found"
},"405": {
"description": "Validation exception"
}
},"read:pets"
]
}
]
}
},"/pet/findByStatus": {
"get": {
"tags": [
"pet"
],"summary": "根据状态查找宠物","description": "Multiple status values can be provided with comma seperated strings","operationId": "findPetsByStatus","parameters": [
{
"name": "status","in": "query","description": "Status values that need to be considered for filter","type": "array","items": {
"type": "string","enum": [
"available","pending","sold"
],"default": "available"
},"collectionFormat": "csv"
}
],"responses": {
"200": {
"description": "successful operation","schema": {
"type": "array","items": {
"$ref": "#/definitions/Pet"
}
}
},"400": {
"description": "Invalid status value"
}
},"/pet/findByTags": {
"get": {
"tags": [
"pet"
],"summary": "根据tags查找宠物","description": "Muliple tags can be provided with comma seperated strings. Use tag1,tag2,tag3 for testing.","operationId": "findPetsByTags","parameters": [
{
"name": "tags","description": "Tags to filter by","items": {
"type": "string"
},"400": {
"description": "Invalid tag value"
}
},"/pet/{petId}": {
"get": {
"tags": [
"pet"
],"summary": "根据id查找宠物","description": "Returns a single pet","operationId": "getPetById","parameters": [
{
"name": "petId","in": "path","description": "ID of pet to return","type": "integer","format": "int64"
}
],"schema": {
"$ref": "#/definitions/Pet"
}
},"400": {
"description": "Invalid ID supplied"
},"404": {
"description": "Pet not found"
}
},"security": [
{
"api_key": []
}
]
},"post": {
"tags": [
"pet"
],"summary": "根据表单数据,更新宠物数据","operationId": "updatePetWithForm","consumes": [
"application/x-www-form-urlencoded"
],"description": "ID of pet that needs to be updated","format": "int64"
},{
"name": "name","in": "formData","description": "Updated name of the pet","required": false,"type": "string"
},{
"name": "status","description": "Updated status of the pet","type": "string"
}
],"delete": {
"tags": [
"pet"
],"summary": "删除宠物","operationId": "deletePet","parameters": [
{
"name": "api_key","in": "header",{
"name": "petId","description": "Pet id to delete","responses": {
"400": {
"description": "Invalid pet value"
}
},"/pet/{petId}/uploadImage": {
"post": {
"tags": [
"pet"
],"summary": "更新图片","operationId": "uploadFile","consumes": [
"multipart/form-data"
],"produces": [
"application/json"
],"description": "ID of pet to update",{
"name": "additionalMetadata","description": "Additional data to pass to server",{
"name": "file","description": "file to upload","type": "file"
}
],"schema": {
"$ref": "#/definitions/ApiResponse"
}
}
},"/store/inventory": {
"get": {
"tags": [
"store"
],"summary": "返回宠物库存状态","description": "Returns a map of status codes to quantities","operationId": "getInventory","parameters": [],"schema": {
"type": "object","additionalProperties": {
"type": "integer","format": "int32"
}
}
}
},"security": [
{
"api_key": []
}
]
}
},"/store/order": {
"post": {
"tags": [
"store"
],"summary": "订购一个宠物","operationId": "placeOrder","description": "order placed for purchasing the pet","schema": {
"$ref": "#/definitions/Order"
}
}
],"schema": {
"$ref": "#/definitions/Order"
}
},"400": {
"description": "Invalid Order"
}
}
}
},"/store/order/{orderId}": {
"get": {
"tags": [
"store"
],"summary": "根据ID查找订单","description": "For valid response try integer IDs with value = 5 or > 10. Other values will generated exceptions","operationId": "getOrderById","parameters": [
{
"name": "orderId","description": "ID of pet that needs to be fetched","maximum": 5,"minimum": 1,"404": {
"description": "Order not found"
}
}
},"delete": {
"tags": [
"store"
],"summary": "根据ID删除订单",1)"> 1000. Anything above 1000 or nonintegers will generate API errors","operationId": "deleteOrder","description": "ID of the order that needs to be deleted","type": "string","minimum": 1
}
],"404": {
"description": "Order not found"
}
}
}
},"/user": {
"post": {
"tags": [
"user"
],"summary": "创建用户","description": "This can only be done by the logged in user.","operationId": "createUser","description": "Created user object","schema": {
"$ref": "#/definitions/User"
}
}
],"responses": {
"default": {
"description": "successful operation"
}
}
}
},"/user/createWithArray": {
"post": {
"tags": [
"user"
],"summary": "根据传入数组,创建多个用户","operationId": "createUsersWithArrayInput","description": "List of user object","items": {
"$ref": "#/definitions/User"
}
}
}
],"/user/createWithList": {
"post": {
"tags": [
"user"
],"summary": "根据列表创建多个用户","operationId": "createUsersWithListInput","/user/login": {
"get": {
"tags": [
"user"
],"summary": "用户登录系统","operationId": "loginUser","parameters": [
{
"name": "username","description": "The user name for login",{
"name": "password","description": "The password for login in clear text","schema": {
"type": "string"
},"headers": {
"X-Rate-Limit": {
"type": "integer","format": "int32","description": "calls per hour allowed by the user"
},"X-Expires-After": {
"type": "string","format": "date-time","description": "date in UTC when toekn expires"
}
}
},"400": {
"description": "Invalid username/password supplied"
}
}
}
},"/user/logout": {
"get": {
"tags": [
"user"
],"summary": "用户退出登录,并清除session","operationId": "logoutUser","/user/{username}": {
"get": {
"tags": [
"user"
],"summary": "根据用户名获取用户","operationId": "getUserByName","description": "The name that needs to be fetched. Use user1 for testing. ","schema": {
"$ref": "#/definitions/User"
}
},"400": {
"description": "Invalid username supplied"
},"404": {
"description": "User not found"
}
}
},"put": {
"tags": [
"user"
],"summary": "更新用户","operationId": "updateUser","description": "name that need to be deleted",{
"in": "body","description": "Updated user object","responses": {
"400": {
"description": "Invalid user supplied"
},"delete": {
"tags": [
"user"
],"summary": "删除用户","operationId": "deleteUser","description": "The name that needs to be deleted","responses": {
"400": {
"description": "Invalid username supplied"
},"404": {
"description": "User not found"
}
}
}
}
},"securityDefinitions": {
"petstore_auth": {
"type": "oauth2","authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog","flow": "implicit","scopes": {
"write:pets": "modify pets in your account","read:pets": "read your pets"
}
},"api_key": {
"type": "apiKey","name": "api_key","in": "header"
}
},"definitions": {
"Order": {
"type": "object","properties": {
"id": {
"type": "integer","format": "int64"
},"petId": {
"type": "integer","quantity": {
"type": "integer","format": "int32"
},"shipDate": {
"type": "string","format": "date-time"
},"status": {
"type": "string","description": "Order Status","enum": [
"placed","approved","delivered"
]
},"complete": {
"type": "boolean","default": false
}
},"xml": {
"name": "Order"
}
},"Category": {
"type": "object","name": {
"type": "string"
}
},"xml": {
"name": "Category"
}
},"User": {
"type": "object","username": {
"type": "string"
},"firstName": {
"type": "string"
},"lastName": {
"type": "string"
},"email": {
"type": "string"
},"password": {
"type": "string"
},"phone": {
"type": "string"
},"userStatus": {
"type": "integer","description": "User Status"
}
},"xml": {
"name": "User"
}
},"Tag": {
"type": "object","xml": {
"name": "Tag"
}
},"Pet": {
"type": "object","required": [
"name","photoUrls"
],"category": {
"$ref": "#/definitions/Category"
},"name": {
"type": "string","example": "doggie"
},"photoUrls": {
"type": "array","xml": {
"name": "photoUrl","wrapped": true
},"items": {
"type": "string"
}
},"tags": {
"type": "array","xml": {
"name": "tag","items": {
"$ref": "#/definitions/Tag"
}
},"description": "pet status in the store","enum": [
"available","sold"
]
}
},"xml": {
"name": "Pet"
}
},"ApiResponse": {
"type": "object","properties": {
"code": {
"type": "integer","type": {
"type": "string"
},"message": {
"type": "string"
}
}
}
},"externalDocs": {
"description": "了解一下我们吧!","url": "https://github.com/helei112g"
}
}
写完后,配置好后,maven build一下 然后打开浏览器输入相对应的网址:localhost:8080/apidoc 就会出来一个文档界面 文档界面出来后,根据自己需要,模仿swagger.json文件,自己修改添加删除改造成自己想要的那样 ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |