项目中需要开放接口供对接方调试,需要简单的web界面,故选择SpringMVC进行HTTP接口开发,SwaggerUI作为用户界面,做接口调用。
一、搭建SpringMVC工程
1、新建maven工程
具体见另一篇文章:https://blog.csdn.net/eleanoryss/article/details/80001890
创建成功之后的maven工程如下:
2、加入Spring依赖
本示例很简单,所以引入几个jar包即可,完整的pom.xml文件内容如下:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.maven.example.webgroupId>
<artifactId>swagger-rocketmqartifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<name>swagger-rocketmq Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<spring.framework.version>4.3.6.RELEASEspring.framework.version>
properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.8.9version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.framework.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.framework.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.framework.version}version>
dependency>
dependencies>
<build>
<finalName>swagger-rocketmqfinalName>
build>
project>
3、编写spring-mvc.xml文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.swagger" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean name="propertyConfigure"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:configInfo.propertiesvalue>
list>
property>
bean>
beans>
4、配置web.xml
<web-app version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<display-name>Archetype Created Web Applicationdisplay-name>
<servlet>
<servlet-name>spring-mvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
<async-supported>trueasync-supported>
servlet>
<servlet-mapping>
<servlet-name>spring-mvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
5、编写HTTP接口
写一个简单的根据ID查询产品信息的方法
产品信息实体:Product.java
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
/**ID*/
private Long id;
/**产品名称*/
private String name;
/**产品型号*/
private String productClass;
/**产品ID*/
private String productId;
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the productClass
*/
public String getProductClass() {
return productClass;
}
/**
* @param productClass
* the productClass to set
*/
public void setProductClass(String productClass) {
this.productClass = productClass;
}
/**
* @return the productId
*/
public String getProductId() {
return productId;
}
/**
* @param productId
* the productId to set
*/
public void setProductId(String productId) {
this.productId = productId;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", productClass=" + productClass + ", productId=" + productId + "]";
}
}
HTTP查询接口:ProductController.java
@RestController
@RequestMapping(value = { "/product/"})
public class ProductController {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity get(@PathVariable Long id) {
Product product = new Product();
product.setName("空气净化器");
product.setId(1L);
product.setProductClass("filters");
product.setProductId("T12345");
return ResponseEntity.ok(product);
}
}
在方法中直接返回的写死的数据,因为只是一个示例代码。
6、验证该端口能否访问
在本地Tomcat运行该工程,访问如下地址:
http://localhost:8080/swagger-rocketmq/product/1/
成功返回信息
至此,我们完成了一个简单的web接口。
二、引入SwaggerUI
1、加入SpringFox-Swagger依赖
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.7.0version>
dependency>
2、加入SpringFox-Swagger-UI依赖
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.7.0version>
dependency>
3、添加SwaggerConfig
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("开放接口API")
.description("HTTP对外开放接口")
.version("1.0.0")
.termsOfServiceUrl("http://xxx.xxx.com")
.license("LICENSE")
.licenseUrl("http://xxx.xxx.com")
.build();
}
}
4、配置访问swaggerUI静态资源
swagger-ui中使用的静态资源文件(如 swagger-ui.html )放在spingfox-swagger-ui-2.7.0.jar中的/META-INF/resources/下:
在spring-mvc.xml文件中加入如下配置:
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**"
location="classpath:/META-INF/resources/webjars/" />
三、添加API接口说明
1、在ProductController.java中加入注释
@RestController
@RequestMapping(value = { "/product/"})
@Api(value = "/ProductController", tags = "接口开放示例")
public class ProductController {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ApiOperation(value = "根据id获取产品信息", notes = "根据id获取产品信息", httpMethod = "GET", response = Product.class)
public ResponseEntity get(@PathVariable Long id) {
Product product = new Product();
product.setName("空气净化器");
product.setId(1L);
product.setProductClass("filters");
product.setProductId("T12345");
return ResponseEntity.ok(product);
}
}
2、访问如下地址:
http://localhost:8080/swagger-rocketmq/swagger-ui.html
页面如下:
在参数id栏中输入任意数字1,然后点击Try it out,可查看接口调用结果,结果如下:
至此,SpringMVC整合SwaggerUI的实例就完成了。
上面涉及到的知识点简单介绍:
1、swagger
swagger可以根据业务代码自动生成相关的api接口文档,尤其用于restful风格中的项目,开发人员几乎可以不用专门去维护rest api,这个框架可以自动为你的业务代码生成restfut风格的api,而且还提供相应的测试界面,自动显示json格式的响应。大大方便了后台开发人员与前端的沟通与联调成本。
2、SpringFox-swagger
spring充分利用自已的优势,把swagger集成到自己的项目里,整了一个spring-swagger,后来便演变成springfox。springfox本身只是利用自身的aop的特点,通过plug的方式把swagger集成了进来,它本身对业务api的生成,还是依靠swagger来实现。
3、SpringFox
SpringFox的大致原理是:在项目启动时,spring上下文在初始化的过程,框架自动跟据配置加载一些swagger相关的bean到当前的上下文中,并自动扫描系统中可能需要生成api文档那些类,并生成相应的信息缓存起来。如果项目MVC控制层用的是springMvc那么会自动扫描所有Controller类,跟据这些Controller类中的方法生成相应的api文档。
参考:
https://my.oschina.net/wangmengjun/blog/907679
https://blog.csdn.net/w4hechuan2009/article/details/68892718
实际合入SpringMVC后出现的问题:
1、只有某些类需要开放给第三方调用或者调试,其他接口在SwaggerUI中不可见
解决办法:
在SwaggerConfig.java中修改:
将RequestHandlerSelectors.any()修改为RequestHandlerSelectors.withClassAnnotation(Api.class),可以选择只显示添加了@Api注释的类。
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.build()
.apiInfo(apiInfo());
}