Spring Boot中整合使用wagger2
阿新 • • 發佈:2019-01-11
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#