Spring Boot中整合使用Swagger2构建RESTful APIs
在之前创建的入门级SpringBoot项目添加swagger2生产接口文档
-
创建swagger2配置类
其实这个配置类,只要了解具体能配置哪些东西就好了,这个swagger2配置启动一次之后就不需要改动了。
特别要注意的是里面配置了api文件也就是controller包的路径,不然生成的文档扫描不到接口。
package com.iamapsycho;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ParameterBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.schema.ModelRef; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Parameter; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import java.util.List; @Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi() { ParameterBuilder tokenPar = new ParameterBuilder(); List<Parameter> pars = new ArrayList<>(); tokenPar.name("Authorization").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build(); pars.add(tokenPar.build()); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.iamapsycho.controller")) .paths(PathSelectors.any()) .build() .globalOperationParameters(pars); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2构建RESTful APIs") .description("springboot项目接口文档") .termsOfServiceUrl("") .contact("iamapsycho") .version("1.0") .build(); } }
-
接下来就可以使用swagger2了!
HelloWorld的Controller类改动:
package com.iamapsycho.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Controller @Api(value = "helloworld测试") public class HelloWorldController { @ResponseBody @RequestMapping(value="/helloworld", method = { RequestMethod.GET, RequestMethod.POST }) @ApiOperation(value="只是一个测试", notes="测试") public String helloWorld(){ return "Hello World! This is Spring Boot !!!"; } }
-
swagger2的访问方法
启动SpringBoot项目之后,访问web地址:http://localhost:8080/SpringBootTest/swagger-ui.html#