如何在Maven clean package时自动生成JSON Schema并解决工具安装报错
解决Spring Boot Maven项目中自动生成JSON Schema的问题
一、修复openapi2jsonschema安装报错
你遇到的安装错误是因为Python 3.11与openapi2jsonschema依赖的PyYAML 5.4.1不兼容,导致编译阶段出现AttributeError: cython_sources。解决方案是通过虚拟环境隔离依赖,并指定兼容Python 3.11的PyYAML版本。
二、编写Python自动化脚本
在项目根目录创建generate_jsonschema.py脚本,它会自动完成虚拟环境创建、依赖安装、Schema生成的全流程:
import os import subprocess import sys from pathlib import Path import shutil # 自定义配置,根据你的项目路径调整 PROJECT_ROOT = Path(__file__).parent YAML_SOURCE_DIR = PROJECT_ROOT / "src/main/resources" # YAML文件存放目录 SCHEMA_OUTPUT_DIR = PROJECT_ROOT / "target/jsonschemas" # Schema输出目录 VENV_DIR = PROJECT_ROOT / ".schema_venv" def create_virtual_env(): # 创建隔离的虚拟环境 subprocess.run([sys.executable, "-m", "venv", str(VENV_DIR)], check=True) def install_dependencies(): # 在虚拟环境中安装兼容版本的依赖 pip_path = VENV_DIR / "Scripts" / "pip.exe" if os.name == "nt" else VENV_DIR / "bin" / "pip" subprocess.run( [str(pip_path), "install", "openapi2jsonschema==0.9.1", "PyYAML==6.0.1"], check=True ) def generate_jsonschemas(): # 创建输出目录(不存在则自动创建) SCHEMA_OUTPUT_DIR.mkdir(parents=True, exist_ok=True) # 调用openapi2jsonschema生成Schema openapi_cli = VENV_DIR / "Scripts" / "openapi2jsonschema.exe" if os.name == "nt" else VENV_DIR / "bin" / "openapi2jsonschema" for yaml_file in YAML_SOURCE_DIR.rglob("*.yaml"): print(f"Processing file: {yaml_file.name}") subprocess.run( [ str(openapi_cli), "--output", str(SCHEMA_OUTPUT_DIR / f"{yaml_file.stem}.json"), str(yaml_file) ], check=True ) def cleanup_venv(): # 清理临时虚拟环境,避免占用磁盘空间 if VENV_DIR.exists(): shutil.rmtree(VENV_DIR) if __name__ == "__main__": try: create_virtual_env() install_dependencies() generate_jsonschemas() finally: cleanup_venv() print("✅ JSON Schema generation completed successfully!")
三、Maven配置集成
在项目pom.xml中添加exec-maven-plugin,将脚本绑定到compile阶段,这样执行mvn clean package时会自动触发Schema生成:
<build> <plugins> <!-- 其他已有插件... --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.1.0</version> <executions> <execution> <id>generate-jsonschema</id> <!-- 在编译阶段执行脚本,确保打包前完成Schema生成 --> <phase>compile</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>python</executable> <arguments> <argument>${project.basedir}/generate_jsonschema.py</argument> </arguments> <!-- 可选:如果需要打印脚本输出,开启下面的配置 --> <outputDirectory>${project.build.directory}</outputDirectory> <outputFile>schema-generate.log</outputFile> </configuration> </execution> </executions> </plugin> </plugins> </build>
四、验证执行
- 确保你的系统已安装Python 3.8+(Python 3.11完全兼容)
- 执行命令:
mvn clean package - 查看
target/jsonschemas目录,会生成对应YAML文件的JSON Schema
内容的提问来源于stack exchange,提问作者todododo
相关产品推荐
相关产品推荐

