社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
最近项目需要使用到swagger,目前官方还没有自己的starter使用,我们上次在文章Swagger2(starter版本)在SpringBoot下的使用使用了程序猿DD翟永超大佬写的spring-boot-starter-swagger版本来通过starter版本更快速的使用Swagger,现在我根据自己的需要也写了一个starter版本,欢迎使用和交流啊(σ゚∀゚)σ..:*☆哎哟不错哦
源码->https://github.com/Yunlingfly/swagger2-starter
引入->https://search.maven.org/artifact/cn.yunlingfly/swagger-spring-boot-starter/0.1-RELEASE/jar
使用方法戳->https://github.com/Yunlingfly/swagger2-starter#swagger-spring-boot-starter
首先给出项目结构
新建springboot项目,更新pom.xml如下(pom详解戳我的另一篇博文->SpringBoot项目发布到Maven中央仓库)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.yunlingfly</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>0.1-RELEASE</version>
<name>swagger-spring-boot-starter</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<!-- lombok省略getter、setter方法 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!--<plugin>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-maven-plugin</artifactId>-->
<!--</plugin>-->
<!-- Springboot的项目打包给其他项目用的话不能使用自带的打包插件,使用下面的 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- sonatype提供了自动release的插件,这意味着运行mvn clean deploy后不用手动去close-> release了,此插件会自动release我们的项目到Maven中央仓库。 -->
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.7</version>
<extensions>true</extensions>
<configuration>
<serverId>oss</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
</plugins>
</build>
</project>
1 首先编写读取yaml配置的SwaggerProperties:
package cn.yunlingfly.swaggerspringbootstarter.infra.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Swagger属性配置
*
* @author yunlingfly@csdn
*/
@Component
@ConfigurationProperties(prefix = "swagger")
@Data
public class SwaggerProperties {
/**
* 标题,必填
*/
private String title;
/**
* 维护人
*/
private Contact contact = new Contact();
/**
* 版本
*/
private String version;
/**
* 描述,必填
*/
private String description;
/**
* swagger扫描的基础包,必填
*/
private String basePackage = "";
/**
* 需要处理的基础URL规则,默认:/**
*/
private String basePath = "/**";
/**
* 需要排除的URL规则,默认:空
*/
private String excludePath = "";
/**
* 许可证
*/
private String license;
private String licenseUrl;
@Data
public static class Contact {
/**
* 维护人名
*/
private String name;
/**
* 维护人email
*/
private String email;
/**
* 维护人url
*/
private String url;
}
}
2 编写校验类SwaggerCondition
package cn.yunlingfly.swaggerspringbootstarter.infra.condition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;
/**
* 校验类
*
* @author yunlingfly@csdn
*/
public class SwaggerCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String title = context.getEnvironment().getProperty("swagger.title");
String description = context.getEnvironment().getProperty("swagger.description");
String basePackage = context.getEnvironment().getProperty("swagger.base-package");
if (StringUtils.isEmpty(title)) {
throw new RuntimeException("Lack of swagger configuration:swagger.title");
} else if (StringUtils.isEmpty(description)) {
throw new RuntimeException("Lack of swagger configuration:swagger.description");
} else if (StringUtils.isEmpty(basePackage)) {
throw new RuntimeException("Lack of swagger configuration:swagger.base-package");
} else {
return true;
}
}
}
3 编写自动装配类SwaggerServiceAutoConfiguration
package cn.yunlingfly.swaggerspringbootstarter;
import cn.yunlingfly.swaggerspringbootstarter.infra.condition.SwaggerCondition;
import cn.yunlingfly.swaggerspringbootstarter.infra.config.SwaggerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* swagger属性配置
*
* @author yunlingfly@csdn
*/
// 装配配置属性
@Configuration
// 自动装配这个properties类,读取yaml自定义内容
@EnableConfigurationProperties(SwaggerProperties.class)
// 校验类
@Conditional(SwaggerCondition.class)
// 当配置文件中 swagger 的值为 true 时,实例化此类。可以不填
@ConditionalOnProperty(prefix = "swagger", value = "true", matchIfMissing = true)
public class SwaggerServiceAutoConfiguration extends WebMvcConfigurationSupport {
@Autowired
private SwaggerProperties swaggerProperties;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title(swaggerProperties.getTitle())
//创建人
.contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail()))
//版本号
.version(swaggerProperties.getVersion())
//描述
.description(swaggerProperties.getDescription())
.build();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(swaggerProperties.getBasePath()).addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
// 解决跨域问题
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
.allowCredentials(true).maxAge(3600);
}
}
4 自定义启动注解EnableYLFSwagger2
package cn.yunlingfly.swaggerspringbootstarter;
import org.springframework.context.annotation.Import;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.lang.annotation.*;
/**
* 启用注解:@EnableYLFSwagger2
*
* @author yunlingfly@csdn
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({SwaggerServiceAutoConfiguration.class})
@EnableSwagger2
public @interface EnableYLFSwagger2 {
}
5 写完后就可以发布到maven中央仓库了(如果只是本地用的话直接install就可以在本地m2仓库找到并引用了):
mvn clean deploy -P release
1 新建springboot项目,引入依赖
<dependency>
<groupId>cn.yunlingfly</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>0.1-RELEASE</version>
</dependency>
2 修改application.yml(这里写配置的时候IDEA会有代码提示的哦):
server:
port: 8072
swagger:
# 标题
title: "Spring Boot 使用 Swagger2 构建RESTful API"
contact:
# 维护人
name: "yunlingfly"
email: "508821881@qq.com"
url: "https://www.yunlingfly.cn"
# 版本
version: "1.0"
# 描述
description: "API 描述"
# swagger扫描的基础包,默认:全扫描
base-package: "cn.yunlingfly.test.api.controller"
# 需要处理的基础URL规则,默认:/**
base-path: "/**"
license: "Apache License, Version 2.0"
license-url: "https://www.apache.org/licenses/LICENSE-2.0.html"
记得在启动类使用注解
package cn.yunlingfly.test;
import cn.yunlingfly.swaggerspringbootstarter.EnableYLFSwagger2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableYLFSwagger2
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
之后就可以随便编写一个controller,然后使用@Api、@ApiOperation、@ApiImplicitParam等注解来丰富swagger了,可以参考我的另一篇博客->Swagger2在SpringBoot下的使用
然后就可以启动项目了~,访问http://localhost:8072/swagger-ui.html就可以看到界面了
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!