如何正确使用从 swagger 规范生成的服务器存根?

2022-01-22 00:00:00 swagger java eclipse maven swagger-codegen

我正在使用 Swagger 2.0 和 swagger-codegen(实际上是 Maven 的 swagger-codegen-plugin)来指定、记录和生成 API,以 Java 作为目标语言.

I'm using Swagger 2.0 and swagger-codegen (actually the swagger-codegen-plugin for Maven) to specify,document and generate an API, with Java as the target language.

该项目已设置为构建服务器存根 (JAX-RS) 和文档,并且 Eclipse 可以识别项目 buildPath 中生成的代码.

The project is already setup to build the server stubs (JAX-RS) and documentation, and Eclipse recognizes the generated code in the project buildPath.

我不确定这里的正确工作流程是什么.:-/

I'm not sure of what is the proper workflow from here. :-/

我认为我不应该修改生成的类,否则每当我更改 swagger 规范时,我的更改都会被覆盖,我希望随着开发的进行,我会更多地考虑 API,它会发生变化.

I don't think I should modify the generated classes, otherwise my changes would be overwritten whenever I change the swagger spec, an I expect it will change as I think more about the API as the development goes on.

那我该怎么办?从生成的类(哪些?)继承或将它们包含在我自己的类中?

What should I do then? Inherit from the generated classes (which ones?) or include them in my own classes?

推荐答案

这里的解决方法有两个步骤.

There are two steps to the solution here.

  1. 将 **/*Controller.java 或 **/*Impl.java 添加到 .swagger-codegen-ignore 文件.根据使用的语言,默认实现在 *Controller.java 或 *Impl.java 文件中提供.一旦从生成中排除默认实现,您就可以在自己的类中实现生成的接口.你自己类中的代码不会在 mvn clean 上刷新.

  1. Add **/*Controller.java or **/*Impl.java to .swagger-codegen-ignore file. Depending on the language used the default implementation is provided in a *Controller.java or *Impl.java file. Once the default implementation is excluded from generation, you can implement the generated interfaces in your own class. The code in your own class will not get refreshed on mvn clean.

.swagger-codegen-ignore 文件本身是一个自动生成的文件,因此当您执行 mvn clean 时,您在步骤 1 中添加的任何内容都会刷新.为避免这种情况,请将您的 .swagger-codegen-ignore 版本保留在资源文件夹中,并将以下插件添加到您的 pom 中,以便在 Maven 生命周期开始时复制文件:

.swagger-codegen-ignore file itself is an auto-generated file hence whatever you add in step 1 gets refreshed when you do a mvn clean. To avoid this keep your version of .swagger-codegen-ignore in your resources folder and add the below plugin to your pom, to copy the file at the start of the Maven lifecycle:

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-resources-plugin</artifactId>
	<executions>
		<execution>
			<id>copy-resources</id>
			<phase>initialize</phase>
			<goals>
				<goal>copy-resources</goal>
			</goals>
			<configuration>
				<outputDirectory>${project.build.directory}/generated/swagger</outputDirectory>
				<resources>
					<resource>
						<directory>${basedir}/src/main/resources</directory>
						<includes>
							<include>.swagger-codegen-ignore</include>
						</includes>
					</resource>
				</resources>
			</configuration>
		</execution>
	</executions>
</plugin>

相关文章