[spring] Invalid default values for arrays and maps on API method declarations
Created by: rubms
Description
When parameters of type array are added to an operation, the generated Spring
code includes an invalid defaultValue
in the Spring MVC parameter annotations. For instance, an array of strings query parameter would generate a Spring code like the following:
@Valid @RequestParam(value = "stringArrayParam", required = false, default="new ArrayList<>()") List<String> stringArrayParam
That generated defaultValue
is invalid: the Spring MVC application will throw an error when a request is performed with no value specified for the parameter.
openapi-generator version
Reproduced with openapi-generator v3.3.3 and previous versions.
OpenAPI declaration file content or url
openapi: 3.0.0
info:
description: "Spec for testing the default value of array parameters"
version: 1.0.0
title: Array parameters test case.
paths:
/pets:
get:
operationId: getPets
summary: Pets.
description: "Get pets."
parameters:
- name: stringArrayParam
in: query
description: "Test array query parameter"
required: false
schema:
type: array
items:
type: string
tags:
- Pets
responses:
200:
description: Successful request.
components:
schemas:
ExampleObject:
type: object
properties:
arrayProperty:
type: array
items:
type: string
Command line used for generation
java -jar openapi-generator-cli-3.3.3.jar generate -g spring -i test.yml -o test
Additionally, the configuration property library
is set to spring-mvc
:
{
"library": "spring-mvc"
}
Steps to reproduce
- Generate a Spring-MVC server application from the previous specification.
- Run the application.
- Throw a GET request to the
/pets
path (getPets
operation) leaving thestringArrayParam
query parameter blank or unspecified.
The server will throw the following error:
Related issues/PRs
This is related to #890, though not the same issue.
Suggest a fix/enhancement
The problem is that there are 2 different cases with respect to default values:
- The default value specified by the user, that should be included as default value in the Spring MVC API method annotations.
- The default variable initializer, which may be affected by the default value specified by the user but differs in data-types like arrays or maps.
However the Spring code generator uses the same value (the default variable initializer, in my opinion) for both: initializing variables and specifying Spring MVC annotations.
The Spring MVC code generator must use a different "default value" for both cases.