Search code examples
spring-bootopenapi-generator

Using @GetMapping instead of @RequestMapping in OpenAPI Spring generator?


Using the OpenAPI Generator for Spring, the Gradle plugin generates my interface with the @RequestMapping annotations. Is it also possible to generate classes with the concrete HTTP method annotation, for example, @GetMapping?

Though I cannot find an option like this in the documentation, this blog post seems to use this kind of annotation:

https://www.baeldung.com/java-openapi-generator-server


Solution

  • With OpenAPI Generator, you can generate Spring controllers with specific HTTP method annotations like @GetMapping, @PostMapping, etc. instead of generic @RequestMapping annotations. This can be achieved by configuring the generator properly in your OpenAPI specification file or via command-line options.

    In your OpenAPI specification file, you can specify the operation level x-spring-annotations attribute to control the Spring annotations generated for each operation. For example:

    paths:
      /example:
        get:
          x-spring-annotations:
            operation: "@GetMapping"
    

    This should help to solve the issue.

    In summary, if you prefer a more compact and self-contained specification, the @RequestMapping approach might be suitable. However, if you value separation of concerns and keeping the OpenAPI specification focused solely on defining endpoints, the second approach could be better. Ultimately, it's a matter of preference and the specific requirements of your project.