如何将Swagger生成的类包含在项目目录中

huangapple go评论85阅读模式
英文:

How to include swagger generated classes in project directory

问题

我正在尝试使用Swagger Codegen为我的Spring Boot项目生成模型类。我在网上找到了一些参考资料,并在我的pom.xml中包含了以下插件:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>
                    ${project.basedir}/src/main/resources/Contract-v1.yml
                </inputSpec>
                <generatorName>spring</generatorName>
                <apiPackage>${project.groupId}.swagger.api</apiPackage>
                <modelPackage>${project.groupId}.swagger.model</modelPackage>
                <supportingFilesToGenerate>
                    ApiUtil.java
                </supportingFilesToGenerate>
                <configOptions>
                    <sourceFolder>src/main/java/</sourceFolder>
                    <delegatePattern>true</delegatePattern>
                    <interfaceOnly>true</interfaceOnly>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

我运行了mvn install命令,类被生成在目录/target/generated-sources/openapi中。但我无法在我的REST控制器类中导入这些生成的类。

我的理解是<modelPackage>字段用于标识生成的类应放置在哪个包中。我对此理解正确吗?

尽管这些生成的类位于正确的包中,但由于它们不在src/main/java目录中,我可能无法在其他类中导入它们。

是否有方法可以将这些生成的类放在src/main/java目录下,或者是因为我的Maven配置中缺少了某些内容,导致其他类无法访问这些文件?

英文:

I am trying to use Swagger Codegen to generate model classes for my spring boot project. I found some references online and included the following plugin in my pom.xml:

		&lt;plugin&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
		&lt;/plugin&gt;

		&lt;plugin&gt;
			&lt;groupId&gt;org.openapitools&lt;/groupId&gt;
			&lt;artifactId&gt;openapi-generator-maven-plugin&lt;/artifactId&gt;
			&lt;executions&gt;
				&lt;execution&gt;
					&lt;goals&gt;
						&lt;goal&gt;generate&lt;/goal&gt;
					&lt;/goals&gt;
					&lt;configuration&gt;
						&lt;inputSpec&gt;
							${project.basedir}/src/main/resources/Contract-v1.yml
						&lt;/inputSpec&gt;
						&lt;generatorName&gt;spring&lt;/generatorName&gt;
						&lt;apiPackage&gt;${project.groupId}.swagger.api&lt;/apiPackage&gt;
						&lt;modelPackage&gt;${project.groupId}.swagger.model&lt;/modelPackage&gt;
						&lt;supportingFilesToGenerate&gt;
							ApiUtil.java
						&lt;/supportingFilesToGenerate&gt;
						&lt;configOptions&gt;
							&lt;sourceFolder&gt;src/main/java/&lt;/sourceFolder&gt;
							&lt;delegatePattern&gt;true&lt;/delegatePattern&gt;
							&lt;interfaceOnly&gt;true&lt;/interfaceOnly&gt;
						&lt;/configOptions&gt;
					&lt;/configuration&gt;
				&lt;/execution&gt;
			&lt;/executions&gt;
		&lt;/plugin&gt;

I run mvn install and the classes are generated in the directory /target/generated-sources/openapi. But I am unable to import these generated classes in my REST controller class.

My understanding is that the &lt;modelPackage&gt; field is used to identify the package in which the generated classes have to be placed. Am I right about this?

Even though these generated classes are in the right package, since they are not in the src/main/java, i am probably not able to import them in other classes.

Is there way to get these generated classes under the src/main/java directory or am I missing something in the maven config due to which these files are unavailable to other classes ?

答案1

得分: 2

我还想实现您尝试的功能,尽管最初我有些摸索,但最终我找到了解决方法,我不需要做任何特别的事情。其中一个注意事项是,我使用了swagger-codegen-maven-plugin,而不是openapi-generator-maven-plugin

以下是最新版本swagger-codegen-maven-plugin(版本3.0.35)的配置示例。当我运行mvn compile时,所有的类都会生成在目标文件夹中,并且src main java被标记为源代码文件夹。我能够通过引用生成的代码 API 直接在项目中实现自己的控制器。说实话,swagger-codegen-maven-plugin的文档并不是最好的,我不得不查阅多个地方才能理解。以下是一些参考链接:

常规配置参数:
https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen-maven-plugin

配置选项:
https://github.com/swagger-api/swagger-codegen/issues/7795

<plugin>
  <groupId>io.swagger.codegen.v3</groupId>
  <artifactId>swagger-codegen-maven-plugin</artifactId>
  <version>3.0.35</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <inputSpec>${project.basedir}/api-docs/swagger.yaml</inputSpec>

        <generateApis>true</generateApis>
        <generateModels>true</generateModels>
        <generateSupportingFiles>false</generateSupportingFiles>
        <language>spring</language>

        <configOptions>

          <basePackage>com.company.project</basePackage>
          <apiPackage>com.company.project.api</apiPackage>
          <modelPackage>com.company.project.model</modelPackage>

          <interfaceOnly>true</interfaceOnly>
          <sourceFolder>src/main/java</sourceFolder>
          <hideGenerationTimestamp>true</hideGenerationTimestamp>
          <dateLibrary>java11</dateLibrary>
          <ignoreUnknownJacksonAnnotation>true</ignoreUnknownJacksonAnnotation>
          <notNullJacksonAnnotation>true</notNullJacksonAnnotation>
          <dateLibrary>false</dateLibrary>
          <useBeanValidation>true</useBeanValidation>
          <serializableModel>true</serializableModel>

        </configOptions>

      </configuration>
    </execution>
  </executions>
</plugin>

(请注意,此处提供的内容是您所请求的代码翻译部分,已按原样翻译,没有添加其他内容。)

英文:

I also wanted to achieve what you were trying and although I fumbled initially I figured it out eventually, I did not have to do anything special. One caveat is that I used swagger-codegen-maven-plugin instead of the openapi-generator-maven-plugin.

Here is how my configuration look like on the day of latest version
swagger-codegen-maven-plugin version 3.0.35. When I ran mvn compile all my classes were generated in the target folder and src main java was marked as sources folder. I was directly able to implement my own controller directly in the project by referencing the generated code API. Tbh the documentation of swagger-codegen-maven-plugin is not the best , I had to look at several places to make sense. Adding some references

General Configuration parameters:
https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen-maven-plugin

Config Options:
https://github.com/swagger-api/swagger-codegen/issues/7795

&lt;plugin&gt;
        &lt;groupId&gt;io.swagger.codegen.v3&lt;/groupId&gt;
        &lt;artifactId&gt;swagger-codegen-maven-plugin&lt;/artifactId&gt;
        &lt;version&gt;3.0.35&lt;/version&gt;
        &lt;executions&gt;
          &lt;execution&gt;
            &lt;goals&gt;
              &lt;goal&gt;generate&lt;/goal&gt;
            &lt;/goals&gt;
            &lt;configuration&gt;
              &lt;inputSpec&gt;${project.basedir}/api-docs/swagger.yaml&lt;/inputSpec&gt;

              &lt;generateApis&gt;true&lt;/generateApis&gt;
              &lt;generateModels&gt;true&lt;/generateModels&gt;
              &lt;generateSupportingFiles&gt;false&lt;/generateSupportingFiles&gt;
              &lt;language&gt;spring&lt;/language&gt;

              &lt;configOptions&gt;

                &lt;basePackage&gt;com.company.project&lt;/basePackage&gt;
                &lt;apiPackage&gt;com.company.project.api&lt;/apiPackage&gt;
                &lt;modelPackage&gt;com.company.project.model&lt;/modelPackage&gt;

                &lt;interfaceOnly&gt;true&lt;/interfaceOnly&gt;
                &lt;sourceFolder&gt;src/main/java&lt;/sourceFolder&gt;
                &lt;hideGenerationTimestamp&gt;true&lt;/hideGenerationTimestamp&gt;
                &lt;dateLibrary&gt;java11&lt;/dateLibrary&gt;
                &lt;ignoreUnknownJacksonAnnotation&gt;true&lt;/ignoreUnknownJacksonAnnotation&gt;
                &lt;notNullJacksonAnnotation&gt;true&lt;/notNullJacksonAnnotation&gt;
                &lt;dateLibrary&gt;false&lt;/dateLibrary&gt;
                &lt;useBeanValidation&gt;true&lt;/useBeanValidation&gt;
                &lt;serializableModel&gt;true&lt;/serializableModel&gt;

              &lt;/configOptions&gt;

            &lt;/configuration&gt;
          &lt;/execution&gt;
        &lt;/executions&gt;
      &lt;/plugin&gt;

答案2

得分: -1

以下是翻译好的部分:

对于Swagger UI,您需要添加依赖项,并进行一些基本配置。在REST API中,您需要包含一些更改。

您可以参考使用Swagger创建的此API:

在Spring Boot的主应用程序文件中,包含以下代码:

@SpringBootApplication
@EnableSwagger2
public class BlogappApplication {

    public static void main(String[] args) {
        SpringApplication.run(BlogappApplication.class, args);
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors
                        .basePackage("com.example.blogapp.controller"))
                .paths(PathSelectors.regex("/.*"))
                .build().apiInfo(apiEndPointsInfo());
    }

    private ApiInfo apiEndPointsInfo() {
        return new ApiInfoBuilder().title("Spring Boot REST API")
                .description("Blog Application REST API")
                .contact(new Contact("name", "url", "email id"))
                .build();
    }
}

然后,修改每个控制器,如以下代码:

@ApiOperation(value = "删除评论", response = String.class)
@ApiParam(value = "评论ID", required = true)
@ApiImplicitParam(name = "Authorization", value = "访问令牌", required = true, allowEmptyValue = false, paramType = "header", dataTypeClass = String.class, example = "Bearer access_token")
@DeleteMapping
public String delete(@RequestParam String id){
    return commentService.delete(id);
}

在使用这些代码之前,请查看我提供的Heroku Swagger链接。

英文:

For swagger UI you need to give the dependency and need to do some basic configurations and also in REST API you need to include couple of changes

https://blog-api-rest.herokuapp.com/swagger-ui.html#/

You can refer this API created using Swagger

In Spring boot main application file include the following code

@SpringBootApplication
@EnableSwagger2
public class BlogappApplication {

	public static void main(String[] args) {
		SpringApplication.run(BlogappApplication.class, args);
	}

	@Bean
	public Docket api() {
		return new Docket(DocumentationType.SWAGGER_2).select()
				.apis(RequestHandlerSelectors
						.basePackage(&quot;com.example.blogapp.controller&quot;))
				.paths(PathSelectors.regex(&quot;/.*&quot;))
				.build().apiInfo(apiEndPointsInfo());
	}

	private ApiInfo apiEndPointsInfo() {
		return new ApiInfoBuilder().title(&quot;Spring Boot REST API&quot;)
				.description(&quot;Blog Application REST API&quot;)
				.contact(new Contact(&quot;name&quot;, &quot;url&quot;, &quot;email id&quot;))
				.build();
	}
}

And modify each and every controllers like the below code

@ApiOperation(value = &quot;Deleting a comment&quot;, response = String.class)
    @ApiParam(value = &quot;Comment ID&quot;, required = true)
    @ApiImplicitParam(name = &quot;Authorization&quot;, value = &quot;Access Token&quot;, required = true, allowEmptyValue = false, paramType = &quot;header&quot;, dataTypeClass = String.class, example = &quot;Bearer access_token&quot;)
    @DeleteMapping
    public String delete(@RequestParam String id){
        return commentService.delete(id);
    }

Before using the codes go through the heroku swagger link I have given

huangapple
  • 本文由 发表于 2020年10月15日 20:55:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64372072.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定