springboot搭建公共swagger模块
文章引用:https://www.jb51.net/article/169494.htm
文章说明:文章引用一些网络代码,非原创,如有侵权,请及时告知
介绍
微服务开发中很多模块都需要添加swagger插件,如果每个模块都要添加相应的配置和maven,所以想把swagger提成公共的模块common-swagger。
内容
1、创建SwaggerConfig
@Configuration
@EnableSwagger2
@ConditionalOnClass({Docket.class, ApiInfoBuilder.class})
@ConditionalOnProperty(prefix = "swagger", value = "enable", matchIfMissing = true)
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfig {
@Bean
@ConditionalOnMissingBean
public SwaggerProperties swaggerProperties() {
return new SwaggerProperties();
}
@Bean
public Docket createRestApi() {
SwaggerProperties properties = swaggerProperties();
return new Docket(DocumentationType.SWAGGER_2)
//生产环境的时候关闭 Swagger 比较安全
.apiInfo(apiInfo(properties))
.select()
//Api扫描目录
.apis(RequestHandlerSelectors.basePackage(properties.getBasePackage()))
.paths(PathSelectors.any())
.build();
}
//自定义编写页面内容,下面内容会显示带Swagger-ui.html上
private ApiInfo apiInfo(SwaggerProperties properties) {
return new ApiInfoBuilder()
.title(properties.getTitle())
.description(properties.getDescription())
.version(properties.getVersion())
.build();
}
}
2、创建SwaggerProperties 配置相关
@Component
@ConfigurationProperties(prefix = "swagger")
public class SwaggerProperties {
/**
* 子系统
*/
private String title;
/**
* 描述
*/
private String description;
/**
* 版本号
*/
private String version;
/**
* api包路径
*/
private String basePackage;
public String getTitle() {
return title;
}
public SwaggerProperties setTitle(String title) {
this.title = title;
return this;
}
public String getDescription() {
return description;
}
public SwaggerProperties setDescription(String description) {
this.description = description;
return this;
}
public String getVersion() {
return version;
}
public SwaggerProperties setVersion(String version) {
this.version = version;
return this;
}
public String getBasePackage() {
return basePackage;
}
public SwaggerProperties setBasePackage(String basePackage) {
this.basePackage = basePackage;
return this;
}
}
3、加载SwaggerConfig
因为是starter模块,可能他人的项目目录和starter模块的目录不一致,导致加载不到SwaggerConfig类,我们需要使用spring.factories把SwaggerConfig类装载到spring容器。
在resources/META-INF添加
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.yunjin.swagger.config.SwaggerConfig(SwaggerConfig文件地址)
4、使用测试
4.1、添加依赖到项目中common-swagger
4.2、配置swagger.properties文件
在自己项目模块的resources目录下 创建swagger.properties配置
swagger.properties 大致配置如下
swagger.basePackage="swagger扫描项目包路径"
swagger.title="swagger网页显示标题"
swagger.description="swagger网页显示介绍"
4.3、启动类添加@EnableSwaggerPlugins注解。
@EnableSwaggerPlugins
@SpringBootApplication
public class FrontDemoApplication {
public static void main(String[] args) {
SpringApplication.run(FrontDemoApplication.class, args);
}
}
总结
提成公共模块,减少重复性代码。
留言
本人小白,如果问题请私聊评论修改,共同学习,谢谢!