If you’re using the springfox-swagger2 library, you might come across a problem when it comes to generic types (such as Pet<T>). In cases where diamond brackets are used, Swagger will generate an invalid specification, resulting in a validation error in the Swagger Editor (“”$ref values must be RFC3986-compliant percent-encoded URIs”).
The error you get might look like this:

In the above case, Swagger generated a model named Kennel«Pet» from a Kennel<Pet> field. Due to the non-alphanumeric characters, a name like this is invalid for an OpenAPI Specification.
The solution to this problem lies in the Springfox documentation:
By default, types with generics will be labeled with ‘\u00ab'(<<), ‘\u00bb'(>>), and commas. This can be problematic with things like swagger-codegen. You can override this behavior by implementing your own
GenericTypeNamingStrategy
. For example, if you wantedList<String>
to be encoded as ‘ListOfString’ andMap<String, Object>
to be encoded as ‘MapOfStringAndObject’ you could set theforCodeGeneration
customization option totrue
during plugin customization:docket.forCodeGeneration(true|false);
Springfox Documentation
To paraphrase, all we need to do is add forCodeGeneration(true) to the Docket configuration and the model will be generated correctly. Here’s an example Docket configuration with the added change:
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .forCodeGeneration(true); } }
The generated model name is now KennelOfPet.
Be First to Comment