spring mvc 集成 swagger2

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 風(fēng)格的接口文檔,內(nèi)容詳細(xì),極大的減少了前后端的溝通成本,同時確保代碼與文檔保持高度一致,極大的減少維護(hù)文檔的時間。")

? ? ? ? ? ? ? ? .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知識請自行學(xué)習(xí)

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>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容