記得以前寫接口,寫完後會整理一份API接口文檔,而文檔的格式如果沒有具體要求的話,最終展示的文檔則完全決定於開發者的心情。也許多點,也許少點。甚至,接口總是需要適應新需求的,修改了,增加了,這份文檔維護起來就很困難了。於是發現了swagger,自動生成文檔的工具。
因爲自強所以自信。swagger官方更新很給力,各種版本的更新都有。swagger會掃描配置的API文檔格式自動生成一份json數據,而swagger官方也提供了ui來做通常的展示,當然也支持自定義ui的。不過對後端開發者來說,能用就可以了,官方就可以了。
最強的是,不僅展示API,而且可以調用訪問,只要輸入參數既可以try it out.
網上很多文章使用的 maven方式集成swagger。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-version}</version></dependency>
<dependency><groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-version}</version>
</dependency>
SpringMVC配置文件中,配置swagger。
<!-- swagger 配置 -->
<!-- Spring MVC JSON配置 -->
<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean id="fastJsonHttpMessageConverter" class="util.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>避免IE出現下載JSON文件的情況
</list>
</property>
</bean>
</list>
</property>
</bean> -->
<!-- Swagger 注入 -->
<!-- <bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" /> -->
<!-- <bean class="com.fh.api.MySwaggerConfig" /> -->
筆者項目中,這裏不需要再次注入,官方示例中是需要注入的。
編寫swagger啓動配置文件。
package com.fh.api;
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
@EnableWebMvc
@EnableSwagger
public class MySwaggerConfig {
@Autowired
private 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(".*?");
}
private ApiInfo apiInfo()
{
ApiInfo apiInfo = new ApiInfo(
"專利管理系統在線API",
"專利管理系統在線API及接口在線管理,方便開發人員快速尋找接口和測試接口,接口統一命名爲/api/模塊/,<br />項目總指揮:王景雲(15102729618)<br />開發組成員:李天元(13871441419),李小攀,劉陽,江明智<br />前端開發組成員:陳龍,王浩,魏峯",
"My Apps API terms of service",
"[email protected]",
"My Apps API Licence Type",
"My Apps API License URL");
return apiInfo;
}
}
swagger-ui靜態資源可以去swagger官網下載。筆者用的最新版。
配置靜態資源的訪問
<!-- swagger訪問轉向路徑指定 -->
<mvc:resources mapping="/swagger/**" location="/swagger/"/>
如果項目中有權限設置的,需要將swagger/index.html 頁面中生成api文檔的地址過濾,不受限制,否則訪問不了。
到此位置,基本配置結束。啓動項目。就可以訪問了。
Jars下載地址: