swagger在线文档配置
详细文档:https://xiaoxiami.gitbook.io/swagger/swagger-php-wen-dang/openapi-gui-fan
Java中使用步骤:
一、添加swagger依赖:
在pom文件导入依赖:
//导入swagger依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
//导入swagger界面依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
二、配置swagger-ui界面
在项目中增加一个Swagger2Configuration类
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
*swagger在线文档配置
*项目启动后可通过地址:http://host:ip/swagger-ui.html 查看在线文档
*
* @author fkxiaozhou
*/
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class Swagger2Configuration {
@Bean
public Docket wxDocket(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("wx")
.apiInfo(wxApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.fk.demo1.web")) //这里采用包扫描的方式来确定要显示的接口
.paths(PathSelectors.any())
.build();
}
private ApiInfo wxApiInfo(){
return new ApiInfoBuilder()
.title("Demo1")
.description("小程序api")
.termsOfServiceUrl("NO terms of service")
.version("1.0")
.build();
}
}
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//加了ApiOperation注解的类,才生成接口文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//包下的类,才生成接口文档
//.apis(RequestHandlerSelectors.basePackage("io.renren.controller"))
.paths(PathSelectors.any())
.build()
.securitySchemes(security());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("人人开源")
.description("renren-fast文档")
.termsOfServiceUrl("https://www.renren.io")
.version("3.0.0")
.build();
}
private List<ApiKey> security() {
return newArrayList(
new ApiKey("token", "token", "header")
);
}
}
三、使用
配置完成后,启动服务,访问:http://localhost:8080/swagger-ui.html就完成了集成
swagger会默认把所有的Controller中的RequestMapping方法生成API出来,实际上一般只要标准接口(像返回页面的controller方法就不需要),可以按照下面的方式设定要生成API方法的要求。
如下针对RestController注解的类和ResponseBody注解的方式才生成的swagger的API,并且排除了特定的类:
@Configuration
@EnableSwagger2 //启用swagger
public class SwaggerConfig{
@Bean
public Docket creatRestApi(){
Predicate<RequestHandler> predicate = new Predicate<RequestHandler>() {
@Override
public boolean apply(RequestHandler input) {
Class<?> declaringClass = input.declaringClass();
if (declaringClass == BasicErrorController.class)// 排除
return false;
if(declaringClass.isAnnotationPresent(RestController.class)) // 被注解的类
return true;
if(input.isAnnotatedWith(ResponseBody.class)) // 被注解的方法
return true;
return false;
}
};
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.useDefaultResponseMessages(false)
.select()
.apis(predicate)
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("包含媒体、咨询、搜索引擎关键字、广告等类型接口的服务")//大标题
.version("1.0")//版本
.build();
}
}
四、常见的swagger注解一览及使用
最常用的5个注解:
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@Apiproperty:用对象接收参数,描述对象的一个字段
其他若干:
@ApiResponse:Http响应其中一个描述
@ApiResponses:Http响应整体描述
@Apilgnore:使用该注解忽略这个api
@ApiClass
@ApiError
@ApiErrors
@ApiParamImplicit
@ApiparamsImplicit
五、创建两个controller来测试
-
TestController.java
@Controller @RequestMapping("/api/test") public class TestController { @ResponseBody @RequestMapping(value = "/show", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)// 这里指定RequestMethod,如果不指定Swagger会把所有RequestMethod都输出,在实际应用中,具体指定请求类型也使接口更为严谨。 @ApiOperation(value="测试接口", notes="测试接口详细描述") public String show( @ApiParam(required=true, name="name", value="姓名") @RequestParam(name = "name", required=true) String stuName){ return "success"; } }
-
DemoController.java
/** * DemoController * */ @Controller @RequestMapping(value = "/demo") public class DemoController { private Logger logger = LoggerFactory.getLogger(DemoController.class); /** * 可以直接使用@ResponseBody响应JSON * * @param request * @param response * @return */ @ResponseBody @RequestMapping(value = "/getcount", method = RequestMethod.POST) @ApiOperation(value="测试-getCount", notes="getCount更多说明") public ModelMap getCount(HttpServletRequest request, HttpServletResponse response) { logger.info(">>>>>>>> begin getCount >>>>>>>>"); ModelMap map = new ModelMap(); map.addAttribute("count", 158); // 后台获取的国际化信息 map.addAttribute("xstest", "测试"); return map; } /** * 可以直接使用@ResponseBody响应JSON * * @param request * @param response * @return */ @ApiIgnore//使用该注解忽略这个API @ResponseBody @RequestMapping(value = "/jsonTest1", method = RequestMethod.POST) public ModelMap jsonTest(HttpServletRequest request, HttpServletResponse response) { ModelMap map = new ModelMap(); map.addAttribute("hello", "你好"); map.addAttribute("veryGood", "很好"); return map; } /** * 可以直接使用@ResponseBody响应JSON * * @param request * @param response * @return */ @ResponseBody @RequestMapping(value = "/jsonTest3", method = RequestMethod.POST) public List<String> jsonTest3(HttpServletRequest request, HttpServletResponse response) { List<String> list = new ArrayList<String>(); list.add("hello"); list.add("你好"); return list; } /** * JSON请求一个对象<br/> * (Ajax Post Data:{"name":"名称","content":"内容"}) * * @param version * @return */ @ResponseBody @RequestMapping(value = "/jsonTest2", method = RequestMethod.POST) public ModelMap jsonTest2(@RequestBody Demo demo) { logger.info("demoName:" + demo.getName()); logger.info("demoContent:" + demo.getContent()); ModelMap map = new ModelMap(); map.addAttribute("result", "ok"); return map; } /** * 直接读取URL参数值<br/> * /demo/jsonTest6.do?name=Hello&content=World * * @param demoName * @param content * @return */ @ResponseBody @RequestMapping(value = "/jsonTest6", method = RequestMethod.POST) public ModelMap jsonTest6(@RequestParam("name") String demoName, @RequestParam String content) { logger.info("demoName:" + demoName); ModelMap map = new ModelMap(); map.addAttribute("name",demoName + "AAA"); map.addAttribute("content",content + "BBB"); map.addAttribute("date",new java.util.Date()); return map; } /** * JSON请求一个对象,将RequestBody自动转换为JSONObject对象<br/> * (Ajax Post Data:{"name":"名称","content":"内容"}) * * 使用JSONObject请添加依赖 * <dependency> * <groupId>net.sf.json-lib</groupId> * <artifactId>json-lib</artifactId> * <version>2.4</version> * <!--指定jdk版本 --> * <classifier>jdk15</classifier> * </dependency> * * @param version * @return */ @ResponseBody @RequestMapping(value = "/jsonTest5", method = RequestMethod.POST) public ModelMap jsonTest5(@RequestBody JSONObject jsonObject) { String name = jsonObject.getString("name"); logger.info("demoName:" + name); ModelMap map = new ModelMap(); map.addAttribute("demoName",name); return map; } /** * 输入 和输出为JSON格式的数据的方式 HttpEntity<?> ResponseEntity<?> * * @param u * @return */ @ResponseBody @RequestMapping(value = "/jsonTest4", method = RequestMethod.POST) public ResponseEntity<String> jsonTest4(HttpEntity<Demo> demo, HttpServletRequest request, HttpSession session) { //获取Headers方法 HttpHeaders headers = demo.getHeaders(); // 获取内容 String demoContent = demo.getBody().getContent(); // 这里直接new一个对象(HttpHeaders headers = new HttpHeaders();) HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("MyHeaderName", "SHANHY"); ResponseEntity<String> responseResult = new ResponseEntity<String>( demoContent, responseHeaders, HttpStatus.OK); return responseResult; } }
swagger会将所有Controller中的Requestmapping方法都暴露出来,在实际开发中不需要把所有API都提现在文档中查看,这种情况下可以使用@Apilgnore来解决,如果应用在Controller上,当前的Controller中的所有方法都会被忽略,如果应用在方法上,则对应用的方法忽略暴露API。
注解@ApiOperation和@ApiParam可以理解为API说明,如果不进行注解说明Swagger2也是有默认值的