3

I'm trying to generate sever code with swagger codegen. In my model have some custom annotation like @Currency

@Target({ METHOD, FIELD, ANNOTATION_TYPE, PARAMETER })
@Retention(RUNTIME)
@Size(min = 3, max = 3)
@Pattern(regexp=TwintPattern.CURRENCY)
@Constraint(validatedBy = {})
@Documented
public @interface Currency {
    String message() default "{javax.validation.constraints.Size.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Can we let swagger know and generate it also in model class?

Park Jay
  • 249
  • 6
  • 14

3 Answers3

2

Starting from OpenAPI Generators version 6.0.0, for Java language, you can use x-class-extra-annotation out of the box without any customization to the mustache templates.

In your example, if you have a Payment object in your OpenAPI specs and you'd like to use the Currency annotation, it would look like this:

Payment:
  type: object
  x-class-extra-annotation: "@fully.qualified.name.of.Currency(message = \"This is a message to override the default one, in case it's required\")"
  properties:
     # ...

The generated Payment Pojo will look like this:

@fully.qualified.name.of.Currency(message = "This is a message to override the default one, in case it's required")
public class Payment {
   // ... fields, setters, and getters as usual
}

Reference:

Mohamed El-Beltagy
  • 902
  • 10
  • 19
0

It's possible by using custom templates.

E.g.:

  1. Add extension to Open Api spec model:

    Person:
      type: object
      x-validations: "@ValidPerson"
      ...
    
  2. Add fragment to pojo.mustache:

    {{#useBeanValidation}}
     {{#vendorExtensions.x-validations}}
      {{vendorExtensions.x-validations}}
     {{/vendorExtensions.x-validations}}
    {{/useBeanValidation}}
    

Or alternatively, if you don't have an option to add something to the spec, you can implement model post processor and add vendor extension values dynamically.

kairius
  • 395
  • 6
  • 10
0

I've been stuck with the similar problem and as the result made an example for swagger-codegen-cli v3 and gradle: Here it is

This might not be exactly what you wanted. The annotations are defined in java code and used by the generated model code.

It is an elaboration of kairus'es method

I've started with this article - this method also works, but making a new language proved to be unnecessary.

Vitaly Roslov
  • 313
  • 1
  • 8