How to properly use the server stubs generated fro

2019-02-17 07:04发布

问题:

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.

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. :-/

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?

回答1:

There are two steps to the solution here.

  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.

  2. .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>



回答2:

I believe you will need to update the Impl classes, e.g. PetApiServiceImpl.

If you want to skip certain files (e.g. Impl classes) during code regeneration, you can add the files to .swagger-codegen-ignore.