最近自己项目要用到这个方便接口管理 就自己去找了些资料 方便自己用
maven:
pom.xml中添加
<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>
添加完事后 增加一个class
/**
* Created by wjs
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
Contact contact = new Contact("wjs", "", "");
return new ApiInfoBuilder()
.title("前台API接口")
.description("前台API接口")
.contact(contact)
.version("1.1.0")
.build();
}
}
当然spring-mvc.xml中需要增加相应的配置
<bean class="上面这个类对应的地址.SwaggerConfig" />
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
然后就能扫描到你的controller了
注解的说明:
/**
* 根据用户名获取用户对象
* @param name
* @return
*/
@RequestMapping(value="/name/{name}", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "根据用户名获取用户对象", httpMethod = "GET", response = User.class, notes = "根据用户名获取用户对象")
public HashMap<String,String> getUserByName(@ApiParam(required = true, name = "name", value = "用户名") @PathVariable String name) throws Exception{
HashMap<String,String> map = new HashMap<String,String>();
map.put("data","111");
return map;
}
只是测试controller不能直接复制
上述代码是Controller中的一个方法,@ApiOperation注解对这个方法进行了说明,@ApiParam注解对方法参数进行了说明。关于这两个注解的使用,可以参看源码。这样子,Swagger就可以扫描接口方法,得到我们自定义的接口说明内容。
说明:
其中@ApiOperation和@ApiParam为添加的API相关注解,个参数说明如下:
@ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”;其他参数可参考源码;
@ApiParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”
然后启动项目打开浏览器
http://localhost:8080/项目名/swagger-ui.html#/
完事