微服务下,一个项目一般会有不少微服务,每一个须要提供Api接口文档可能会用到Swagger,为方便使用须要引入以通用的Swagger公共模块,更好的来匹配当前项目对外展现的Api文档。git
<dependencies> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency> </dependencies>
@Configuration @Getter @Setter @PropertySource(value= {"classpath:swagger.properties"}) @ConfigurationProperties(prefix = "swagger") public class SwaggerProperties { /** * 标题 */ private String title; /** * 描述 */ private String description; /** * 版本号 */ private String version; /** * api包路径 */ private String basePackage; /** * 联系人 */ private String contactName; }
swagger.version = 1.0 swagger.title = ${spring.application.name} service API Doc swagger.description = API Doc for ${spring.application.name} service. swagger.base-package = com.project swagger.contact-name = Asan
@Configuration
@EnableOpenApi
@ConditionalOnClass({Docket.class, ApiInfoBuilder.class})
@ConditionalOnProperty(prefix = "swagger", value = "enable")
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration {github
@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(); } private ApiInfo apiInfo(SwaggerProperties properties) { Contact contact = new Contact(properties.getContactName(), "", ""); return new ApiInfoBuilder() .title(properties.getTitle()) .description(properties.getDescription()) .contact(contact) .version(properties.getVersion()) .build(); }
}spring
resources下建立META-INF文件夹,建立文件spring.factories,内容以下:api
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.asan.common.swagger.config.SwaggerAutoConfiguration
<dependency> <groupId>com.asan</groupId> <artifactId>common-swagger</artifactId> </dependency>
若是须要自定义Api文档名称,则能够自行在对应yaml配置文件中修改app
# Swagger 配置项 swagger: enable: true title: 自定义的标题 description: 自定义的描述 version: 1.0 base-package: com.asan.controller contact-name: 阿三
swagger.enable=true 开启swagger,生产环境建议不用配置spring-boot