最近自己項目要用到這個方便接口管理 就自己去找了些資料 方便自己用
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#/
完事