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
原文地址:https://www.cnblogs.com/wubenhui/p/9053926.html
时间: 2024-11-08 03:08:48