项目开发协作时,api接口文档写起来很麻烦,现在也有许多工具能做到自动生成api文档的效果,这里介绍中笔者在开发中使用过的工具:swagger,需要的同学请拿走。
闲话少说,上干货:
maven配置:
<!-- Swagger API tools -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-staticdocs</artifactId>
<version>2.5.0</version>
</dependency>
SwaggerConfig :
@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan(basePackages ={"com.thinkgem.jeesite.dida"}) //接口所在的包路径
public class SwaggerConfig extends WebMvcConfigurerAdapter {
@Bean
public Docket createRestApi() {
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
tokenPar.name("x-access-token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.thinkgem.jeesite.dida"))//接口所在的包路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("**项目接口文档:")
.termsOfServiceUrl("http://localhost:8080/flydi")
.contact("**项目组")
.version("1.1.1")
.build();
}
}
接口示例:
@Controller@Api(value="AppLoginController",tags={"app登陆接口"})
public class AppLoginController extends BaseController {
@Autowired
private AppUserService appUserService;
@ApiImplicitParams({
@ApiImplicitParam(name = "phoneNo", paramType="query" ,value = "手机", required = true, dataType = "string"),
@ApiImplicitParam(name = "password", paramType="query" , value = "密码", required = true, dataType = "string")
})
@RequestMapping(value = "${didaPath}/applogin", method = RequestMethod.POST)
public String registered(HttpServletRequest request,HttpServletResponse response) {
String phoneNo = WebUtils.getCleanParam(request, "phoneNo");
String password = WebUtils.getCleanParam(request, "password");
AppUser user = new AppUser();
user.setPhoneNo(phoneNo);
user.setPassword(password);
int i = appUserService.insertUser(user);
ResponseBody re=new ResponseBody();
re.setData(i);
return renderString(response, re);
}
}
访问路径:http://127.0.0.1:8080/flydi/swagger-ui.html
效果图:
测试结果:
有些接口不需要显示的添加注解:
@ApiIgnore
第一次需要maven install 之后才会显示接口。