SpringMVC中使用swagger2

swagger,一個API文檔生成工具,當編寫商業項目時,每個項目之間可能需要調用其他項目的API接口,比如說前後端分離項目,這種時候需要寫API文檔,文檔,程序員最討厭自己寫以及別人不寫的一個東西,而Swagger就可以根據在項目中配置的註解自動生成文檔,那麼接下來就開始添加這個小東西

引入jar包

 <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.4.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.4.0</version>
    </dependency>

添加配置

創建SwaggerConfig配置類

@EnableWebMvc
@EnableSwagger2
@Configuration
public class SwaggerConfig extends WebMvcConfigurationSupport {

	/**
	 * 通過createRestApi函數創建Docket的Bean之後,
	 * apiInfo()用來創建該Api的基本信息(這些基本信息會展現在文檔頁面中)
	 * select()函數返回一個ApiSelectorBuilder實例用來控制哪些接口暴露給Swagger來展現,
	 * apis()函數掃描所有Controller中定義的API, 併產生文檔內容(除了被@ApiIgnore指定的請求)
	 * @return
	 */
	@Bean
	public Docket createRestApi() {

		return new Docket(DocumentationType.SWAGGER_2)
//				.globalOperationParameters(operationParameters)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.any())
				.paths(PathSelectors.any())
				.build();
		
	}

	/**
	 * 創建該Api的基本信息(這些基本信息會展現在文檔頁面中)
	 * @return
	 */
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("標題")
				.termsOfServiceUrl("http://www.itrip.com/auth")
				.contact("[email protected]")
				.version("1.0")
				.build();
	}
}

注意在springMVC配置文件中添加

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />

避免被攔截掉

使用

使用註解在controller類上聲明
@Api(tags = “所在類”) =》 聲明類
@ApiOperation(value = “接口名”,notes = “接口描述”,httpMethod = “發送方式”) = 》 聲明接口
@ApiParam(value = “參數名稱”,name = “參數名”) =》 聲明參數

示例:

@Controller
@Api(tags = "UserController")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation(value = "接口名",notes = "接口描述",httpMethod = "post")
    @RequestMapping(value="login",method= RequestMethod.POST)
    @ResponseBody
    public Dto login(
			@RequestParam("userCode")
			@ApiParam(value = "參數說明",name = "參數名") String userCode){

        ItripUser user = userInfoService.getUserInfo(userCode);

        return DtoUtil.returnDataSuccess(user);
    }
}

注意在聲明方法的時候最好指明接口訪問當時訪問方式,就是@RequestMapping中method屬性,否則swagger文檔中會把所有請求方式的方法顯示,現的特別雜亂,還有@RequestParam最好也加上,否則swagger上的測試功能可能無法使用

全部做完後重啓項目,訪問:** 項目地址/swagger-ui.html**就好了

常見異常:訪問頁面報404

1、檢查是否配置springMVC靜態資源

2、檢查路徑是否正確

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章