5分鐘 springboot 整合swagger2
阿新 • • 發佈:2018-05-18
sed des resources text def mutable rod contact println
springboot 整合swagger2
1.maven配置文件中添加依賴
<properties> <swagger2.version>2.2.2</swagger2.version> </properties> -------------------------------------------------- <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger2.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger2.version}</version> </dependency>
2.添加SwaggerConfig.java 文件
@Configuration @EnableSwagger2 public class SwaggerConfig { @Value("${server.context-path}") private String pathMapping; @Bean public Docket createRestApi() { System.out.println("https://localhost:8443" + pathMapping + "/swagger-ui.html"); return new Docket(DocumentationType.SWAGGER_2) .groupName("test") .genericModelSubstitutes(ResponseEntity.class) .useDefaultResponseMessages(true) .forCodeGeneration(false) .pathMapping(pathMapping) .select() .apis(RequestHandlerSelectors.basePackage("com.weapp.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("標題") .description("描述") .termsOfServiceUrl("服務條款網址") .contact("justubborn") .version("1.0") .build(); }
3.配置靜態資源映射WebMvcConfig.java
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
4.在接口中使用swagger註解(參考官方文檔)
@RestController
@RequestMapping
public class AppUserController {
@Api(name=ApiConstant.GET_USER)
@RequestMapping(value = "/api/v1/user/{id}", method = RequestMethod.GET, produces = "application/json")
public Map<String, String> get(@PathVariable String id){
ImmutableMap<String, String> map = ImmutableMap.of("id", id);
return map;
}
}
5.訪問https://localhost:8443/weapp/swagger-ui.html
5分鐘 springboot 整合swagger2