Swagger使用


原文:https://www.cnblogs.com/liruiloveparents/p/9378327.html

 

 

Swagger學習及生成HTML文檔

Swagger

1、集成springboot

第一步:pom

 <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>

第二步:swagger在springboot中配置

屬性類(省略get/set方法)

/** * swagger配置,生成api * * @author lirui * @date 2018-07-26 */ @ConfigurationProperties(prefix = "hyboot.api") public class HySwaggerProperties { /** * 是否開啟swagger */ private boolean enabled = false; /** * API服務標題 */ private String title; /** * API服務描述 */ private String description; /** * API服務版本 */ private String version; /** * Api負責人相關信息 */ private Leader leader = new Leader(); public static class Leader{ /** * 負責人姓名 */ private String name; /** * 負責人郵箱 */ private String email; } /** * 用於生成api的html靜態文檔,需要配置 */ private Swagger swagger = new Swagger(); public static class Swagger{ /** * api 接口獲取數據地址 */ private String apiUrl; /** * 生成文件的位置 */ private String filePath; } }

配置application.yml

 enabled: false  title: 測試服務api  description: 用於測試  leader:  name: 湯姆  email: tom@163.com  version: 1.0.0

配置類

/** * swagger配置,生成api * * @author lirui * @date 2018-07-26 */ @Configuration @EnableConfigurationProperties({HySwaggerProperties.class}) @EnableSwagger2 public class HySwaggerAutoConfiguration { private Logger logger = LoggerFactory.getLogger(HySwaggerAutoConfiguration.class); @Autowired private ApplicationContext applicationContext; @Autowired private HySwaggerProperties hySwaggerProperties; @Autowired private ServerProperties serverProperties; /** * 定義api生成規則 * * @return */ @Bean public Docket hyApi() { return new Docket(DocumentationType.SWAGGER_2) //group為系統編號(我們spring的id設置為了系統編號) .groupName(applicationContext.getId()) .apiInfo(apiInfo()) //支持協議 .protocols(Set.of("http", "https")) .select() //限制只有在類上加@Api才添加到swagger,默認是都添加的 .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) //限制只有在方法上加@Api才添加到swagger,默認是都添加的 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .build(); } /** * api相關信息 * * @return */ public ApiInfo apiInfo() { return new ApiInfoBuilder() //服務標題 .title(hySwaggerProperties.getTitle() == null ? applicationContext.getId() + "系統服務API" : hySwaggerProperties.getTitle()) //api服務描述 .description(hySwaggerProperties.getDescription()) //api版本 .version(hySwaggerProperties.getVersion()) //聯系人 .contact( new Contact(hySwaggerProperties.getLeader().getName(), "", hySwaggerProperties.getLeader().getEmail())) .build(); } }

第三步:訪問

http://host:port/contentPath/swagger-ui.html

2、生成adoc文件,便於生成HTML/PDF

主要想法是:Swagger2MarkupConverter(可以根據指定url生成adoc文件,用於生成html),如果想調用當前系統生成adoc文件,就必須保證系統啟動完成,這樣才能根據url訪問

第一步:定義生成adoc文件的類

springboot中提供了ApplicationRunner,這個保證了系統啟動完執行其中的run方法,所以只要在run方法中調用Swagger2MarkupConverter#from

/** * 系統運行完執行,用於swagger生成adoc文件,繼而產生api接口Html靜態文件 * 必須是spring管理的Bean才生效 * @author lirui * @date 2018-07-26 */ public class SwaggerCreatAdocRunner implements ApplicationRunner { /** * api 接口獲取數據地址 */ private String apiUrl; /** * 生成文件的位置 */ private String filePath; @Override public void run(ApplicationArguments args) throws Exception { try { //從指定地址獲取數據生成接口文檔 Swagger2MarkupConverter.from(new URL(apiUrl)).build() .toFile(Paths.get(filePath)); } catch (MalformedURLException e) { e.printStackTrace(); } } public String getApiUrl() { return apiUrl; } public void setApiUrl(String apiUrl) { this.apiUrl = apiUrl; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } }

第二步:swagger配置初始化SwaggerCreatAdocRunner

就是在上述HySwaggerAutoConfiguration增加了一個SwaggerCreatAdocRunnerspring的bean定義

(添加了默認不開啟Swagger的配置)

/** * swagger配置,生成api * * @author lirui * @date 2018-07-26 */ @Configuration @EnableConfigurationProperties({HySwaggerProperties.class, ServerProperties.class}) @EnableSwagger2 @ConditionalOnExpression("${hyboot.api.enabled:false}") public class HySwaggerAutoConfiguration { private Logger logger = LoggerFactory.getLogger(HySwaggerAutoConfiguration.class); public static final String LOCALHOST = "127.0.0.1"; @Autowired private ApplicationContext applicationContext; @Autowired private HySwaggerProperties hySwaggerProperties; @Autowired private ServerProperties serverProperties; /** * 定義api生成規則 * * @return */ @Bean public Docket hyApi() { ... } /** * 用於生成swagger API html文檔 * http://localhost:8081/demo/v2/api-docs?group=hyboot-demo * * @return */ @Bean public SwaggerCreatAdocRunner swaggerRunner() { //生成api文檔的數據來源 String apiUrl = hySwaggerProperties.getSwagger().getApiUrl(); String filePath = ClassLoader.getSystemResource("").getPath()+"api"; //解決window系統路徑前帶"/"問題 File file = new File(filePath); filePath = file.getPath(); //設置swagger生成adoc文件啟動類 SwaggerCreatAdocRunner swaggerCreatAdocRunner = new SwaggerCreatAdocRunner(); swaggerCreatAdocRunner.setApiUrl(apiUrl); swaggerCreatAdocRunner.setFilePath(filePath); if (StringUtils.isBlank(apiUrl)) { //端口 int port = serverProperties.getPort(); //項目 String contextPath = serverProperties.getServlet().getContextPath(); String group = applicationContext.getId(); apiUrl = "http://" + LOCALHOST + ":" + port + contextPath + "/v2/api-docs?group=" + group; swaggerCreatAdocRunner.setApiUrl(apiUrl); } return swaggerCreatAdocRunner; } /** * api相關信息 * * @return */ public ApiInfo apiInfo() { ... } }

第三步:利用上訴生成的adoc文件生成HTML靜態文件

這里要用到maven的插件asciidoctor

 <!--增加swagger生成html--> <plugin> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctor-maven-plugin</artifactId> <version>1.5.6</version> <configuration> <sourceDirectory>${project.basedir}/target/classes/</sourceDirectory> <sourceDocumentName>api.adoc</sourceDocumentName> <outputFile>${project.basedir}/target/classes/api.html</outputFile> <backend>html</backend> <sourceHighlighter>coderay</sourceHighlighter> <attributes> <toc>left</toc> </attributes> </configuration> </plugin>

執行mvn asciidoctor:process-asciidoc

在IDEA中直接點擊如圖即可:

生成的HTML靜態文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM