@Configuration
@EnableSwagger2
public class SwaggerConfig {
private ApiInfo apiInfo(){
return new ApiInfoBuilder().title("API接口文档")
.description("Bucks Coffee")
.version("v1.0")
.build();
}
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//- 扫描哪些包
.apis(RequestHandlerSelectors.basePackage("com.fanle.controller"))
//- 所有的api都显示
.paths(PathSelectors.any())
.build();
}
}
pom文件
- 原生swagger
io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2
- knife4j
常见问题 1.Failed to start bean ‘documentationPluginsBootstrapper’…com.github.xiaoymin knife4j-spring-boot-starter 2.0.7
- 解决方式一推荐:降低springboot的版本
- 解决方式二:在启动类上添加@EnableWebMvc,这种方式会导致SpringBoot的@EnableAutoConfiguration失效,坑比较多。建议还是老老实实降低版本,参考博客
放行静态资源
- 原生swagger
@Configuration
public class WebConfig implements WebMvcConfigurer {
@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/");
}
}
- knife4j
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
swagger常用注解
@RestController
@Api(tags = "hello模块",value = "hello接口",description = "用在类上")
public class HelloController {
@GetMapping("/hello")
@ApiOperation("用在方法上")
public String hello(@Valid HelloForm form){
return form.getMsg();
}
}
@Data
@ApiModel
public class HelloForm {
@NotBlank
@Pattern(regexp = "^[0-9]{6}$")
private String msg;
}



