pom
? ? <!-- swagger2核心依賴 -->
? ? <dependency>
? ? ? <groupId>io.springfox</groupId>
? ? ? <artifactId>springfox-swagger2</artifactId>
? ? ? <version>2.6.1</version>
? ? </dependency>
? ? <!-- swagger-ui為項目提供api展示及測試的界面 -->
? ? <dependency>
? ? ? <groupId>io.springfox</groupId>
? ? ? <artifactId>springfox-swagger-ui</artifactId>
? ? ? <version>2.6.1</version>
? ? </dependency>
swagger配置文件
@Configuration
@EnableSwagger2
@EnableWebMvc
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("基礎(chǔ)平臺 RESTful APIs")
? ? ? ? ? ? ? ? .description("基礎(chǔ)平臺 RESTful 風格的接口文檔,內(nèi)容詳細,極大的減少了前后端的溝通成本,同時確保代碼與文檔保持高度一致,極大的減少維護文檔的時間。")
? ? ? ? ? ? ? ? .termsOfServiceUrl("http://xiachengwei5.coding.me")
? ? ? ? ? ? ? ? .contact("Pat")
? ? ? ? ? ? ? ? .version("1.0.0")
? ? ? ? ? ? ? ? .build();
? ? }
}
rest接口可有可無,附上rest api demo
@RestController
@RequestMapping("/pubpay")
@Api(value = "test")
public class TestController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "test",httpMethod = "GET")
public String test() {
return "";
}
}
swagger注解及rest api知識請自行學習
mvc配置文件中配置bean及靜態(tài)資源
<!-- swagger配置文件所在包-->
<context:component-scan base-package="..."/>
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**"
? ? ? ? ? ? ? ? location="classpath:/META-INF/resources/webjars/" />
運行tomcat,訪問路徑為:http://localhost:8080/swagger-ui.html
本人曾遇到的問題
swagger-ui不顯示接口列表
嘗試訪問http://localhost:8080/v2/api-docs,得到的數(shù)據(jù)為{}
查資料得知fastjson版本問題,替換即可:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
替換為:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>