在Ubuntu上配置Swagger的技巧主要包括安装和配置Swagger Editor和Swagger UI,以及使用Springfox自动化生成API文档。以下是详细的步骤和技巧:
安装Swagger Editor和Swagger UI
-
安装Node.js和npm:
sudo apt update sudo apt install -y nodejs npm
-
安装Swagger Editor:
mkdir -p /opt/swagger cd /opt/swagger wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.16.1.tar.gz tar -xvf v3.16.1.tar.gz rm v3.16.1.tar.gz cd Swagger-editor-3.16.1 npm install
-
启动Swagger Editor:
node index.js
然后在浏览器中访问
http://localhost:8081
。 -
安装Swagger UI:
mkdir -p /opt/swagger cd /opt/swagger wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.48.0.tar.gz tar -xvf v3.48.0.tar.gz rm v3.48.0.tar.gz cd swagger-ui-3.48.0 npm install
-
启动Swagger UI:
node index.js
然后在浏览器中访问
http://localhost:8080
。
使用Springfox自动化生成API文档
-
添加Springfox依赖: 在
pom.xml
中添加以下依赖:io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2 -
配置Swagger: 创建一个配置类,例如
SwaggerConfig.java
:import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } }
-
访问Swagger UI: 启动Spring Boot应用后,在浏览器中访问
http://localhost:8080/swagger-ui/
,然后输入配置文件中指定的Swagger JSON文件地址。
其他技巧
-
使用systemd管理Swagger服务: 可以将Swagger Editor和Swagger UI配置为系统服务,实现开机自启。
Swagger文档动态更新: 使用Springfox可以根据代码变化自动更新Swagger文档,减少手动维护的工作量。
通过以上步骤和技巧,你可以在Ubuntu上高效地配置和管理Swagger,提升前后端开发的协作效率。