JavaWeb專案中整合Swagger API文件
阿新 • • 發佈:2018-12-24
0 本文主要涉及
在基於Spring和SpringMVC的前後端分離的JavaWeb專案中生成Swagger API文件(使用SpringFox來實現)。
1 SpringFox和Swagger簡介
結合SpringFox通過註解的形式自動生成Swagger API文件(HTML頁面形式),該文件還具有簡單的介面除錯功能。
官網:http://springfox.github.io/springfox/
2 SpringFox配置整合
0 依賴配置
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
1 SpringBean配置
通過JavaConfig形式在SpringMVC的Bean中寫入資源路徑對映@Configuration @EnableWebMvc @EnableSwagger2 public class SwaggerConfig { @Bean public Docket myDocket() { Docket docket = new Docket(DocumentationType.SWAGGER_2); ApiInfo apiInfo = new ApiInfoBuilder() .title("API介面文件") .description("") .contact(new Contact("", "", "")) .version("1.0") .build(); docket.apiInfo(apiInfo); //設定只生成被Api這個註解註解過的Ctrl類中有ApiOperation註解的api介面的文件 docket.select().apis(RequestHandlerSelectors.withClassAnnotation(Api.class)).apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build(); return docket; } }
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
如果專案使用了Shiro控制頁面訪問許可權需要在過濾器中加入以下配置,方便文件使用<!--swagger介面文件--> /swagger*/**=anon /v2/**=anon /webjars/**=anon
3 Swagger使用示例
@RestController
@RequestMapping("/user")
@Api(tags = "UserinfoCtrl", description = "使用者資訊相關")
public class UserInfoCtrl
{
@Autowired
private UserInfoService userInfoService;
@RequestMapping("/getInfo")
@ApiOperation(value = "獲取使用者資訊", httpMethod = "GET", notes = "顯示使用者資訊,不顯示密碼")
public Object getInfo() throws MyMessageException
{
return userInfoService.getInfo();
}
@RequestMapping("/login")
@ApiOperation(value = "登入", httpMethod = "POST", notes = "說明。。。")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "使用者名稱", required = true, paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "password", value = "密碼(MD5)", required = true, paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "rememberMe", value = "是否記住登入狀態", defaultValue = "false", paramType = "query", dataType = "boolean"),})
public Object login(@Valid LoginVO user, @RequestParam(defaultValue = "false") Boolean rememberMe, HttpServletRequest request) throws Exception
{
//。。。
}
}
生成的文件可在http://host地址:埠/專案名/swagger-ui.html#/中看到