介绍RESTful API的重磅好伙伴Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。
在Spring Boot中使用Swagger2
在pom.xml
中加入Swagger2的依赖:
<!--引入Swagger2的依赖--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
在Application.java
同级创建Swagger2的配置类Swagger2:
package dhccservice.dhccservice; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; 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; @Configuration @EnableSwagger2 public class Swagger2Configure{ @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .useDefaultResponseMessages(false) .select() .apis(RequestHandlerSelectors.basePackage("dhccservice.dhccservice")) //paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2构建RESTful APIs")//大标题 .description("Spring Boot Swagger2")//详细描述 .termsOfServiceUrl("http://www.dhcc.com.cn") .contact("seawater")//作者 .version("1.0")//版本 .build(); } }
通过@Configuration
注解,让Spring来加载该类配置。
再通过@EnableSwagger2
注解来启用Swagger2。
再通过createRestApi
方法创建Docket
的Bean之后,apiInfo()
用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。
select()方法
返回一个ApiSelectorBuilder
实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore
指定的请求)。
使用@ApiOperation
注解来给API增加说明、通过@ApiImplicitParams
、@ApiImplicitParam
注解来给参数增加说明。
@Api(value = "菜单相关操作",protocols ="http",produces = "100") @RestController public class MenuInfoController { @Autowired private MenuInfoService service; @ApiOperation(value="查询菜单所有信息",notes = "查询菜单所有信息",httpMethod = "GET") @ApiImplicitParam(name="menutype",value = "菜单类型",dataType = "String",required = false,paramType = "query") @RequestMapping(value = "/menuInfoAll",method = RequestMethod.GET) public String menuInfoAll(HttpServletRequest request, HttpServletResponse response) { LogWriter.info("dhcc-service","basiccontroller","menuInfoAll"); String arg = request.getQueryString(); arg= PublicUtil.EndecodeStr(arg); String result = service.menuInfoAll(arg); PublicUtil.OutPrint(request, response, result); return null; }
完成上述代码添加上,启动Spring Boot程序,访问:http://localhost:port/swagger-ui.html 就能看到RESTful API的页面。我们可以再点开具体的API请求,以POST类型的/menuInfoAll请求为例,可找到上述代码中我们配置的Notes信息以及参数menutype的描述信息。