swagger:restful管理项目API工具
1、pom.xml增加依赖包
<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>
2、在spring-mvc.xml中声明swagger配置bean
在application.xml添加配置,如果使用spring boot此步骤忽略
<bean class="com.aoji.protal.pc.common.component.Swagger2" id="swagger2Config"/>
java类代码
/**
* Swagger2配置类
* 在与spring boot集成时,放在与Application.java同级的目录下。
* 通过@Configuration注解,让Spring来加载该类配置。
* 再通过@EnableSwagger2注解来启用Swagger2。
*/
@Configuration
@EnableWebMvc
@EnableSwagger2
public class Swagger2 extends WebMvcConfigurationSupport
{
/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.aoji.protal.pc.
h5.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.title("Spring 中使用Swagger2构建RESTful APIs")
.termsOfServiceUrl("http://www.aoji.cn")
.contact("澳际教育")
.version("1.0")
.build();
}
}
3、在spring-mvc.xml中声明swagger配置bean
<mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
如果是spring boot,则需要在WebMvcConfigurerAdapter继承类中加入:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
这是我其中一个项目中的例子:
4、通过以上配置启动项目访问即可看到
localhost:8080/swagger-ui.html
5.依照swagger规范配置接口调用说明
/**
* 分支互动列表
* @return
*/
@RequestMapping(value = "/h5/lecturelist", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value="查询面试活动列表", notes="不传国家码时返回5大国所有的活动列表,每个国家最多返回8条数据")
@ApiImplicitParams({
@ApiImplicitParam(paramType="query", name = "countryCode", value = "国家码", required = false, dataType = "String"),
@ApiImplicitParam(paramType="query", name = "page", value = "分页对象", required = false, dataType = "Page"),
})
public AjaxJson getLectureList(String countryCode,Page page)
{
//代码
}
实体:
@ApiModel(value = "分页对象", description = "分页")
public class Page {
public static final int DEFAUTLPAGESIZE = 10;
public static final int[] OPTIONALPAGESIZE = {10,20,30,40,50,100,200,300,500};
private int total = 0;
@ApiModelProperty(value = "每页数据大小", required = false)
private int pageSize = DEFAUTLPAGESIZE;
private List<? extends Object> data = new ArrayList();
@ApiModelProperty(value = "页码", required = false)
private Integer pageIndex = 1;
6.访问文档截图