openapi: 3.0.1
info:
title: ReviewApis
version: 1.0.0
description: API for managing book reviews
paths:
/create-new-review:
post:
operationId: createNewReview
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Review'
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/Review'
/reviews/{reviewId}:
get:
operationId: getReviewById
parameters:
- name: reviewId
in: path
required: true
schema:
type: string
format: uuid
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/Review'
components:
schemas:
Review:
type: object
required: [title, content, score, bookId]
properties:
id:
type: string
format: uuid
title:
type: string
minLength: 10
maxLength: 100
content:
type: string
minLength: 100
maxLength: 500
score:
type: integer
minimum: 0
maximum: 5
bookId:
type: string
format: uuid
< /code>
Вот команда, которую я использовал: < /p>
openapi-generator-cli generate \
-i ./review-service.yaml \
-o review-models \
-g java \
--enable-post-process-file \
--type-mappings DateTime=java.time.OffsetDateTime,Date=java.time.LocalDate \
--import-mappings DateTime=java.time.OffsetDateTime,Date=java.time.LocalDate \
--additional-properties lombok=true,useBeanValidation=true,dateLibrary=java8,interfaceOnly=true \
--skip-validate-spec
< /code>
Но сгенерированные модели не включают аннотации Lombok или аннотации проверки бобов. Вот класс, который я сгенерировал этой командой, однако он не имеет ни аннотаций Lombok, ни аннотации проверки находятся в полях: < /p>
/*
* ReviewApis
* API for managing book reviews
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Review
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2025-05-07T10:55:55.053337300+02:00[Europe/Berlin]", comments = "Generator version: 7.13.0")
public class Review {
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
@javax.annotation.Nullable
private UUID id;
public static final String SERIALIZED_NAME_TITLE = "title";
@SerializedName(SERIALIZED_NAME_TITLE)
@javax.annotation.Nonnull
private String title;
public static final String SERIALIZED_NAME_CONTENT = "content";
@SerializedName(SERIALIZED_NAME_CONTENT)
@javax.annotation.Nonnull
private String content;
public static final String SERIALIZED_NAME_SCORE = "score";
@SerializedName(SERIALIZED_NAME_SCORE)
@javax.annotation.Nonnull
private Integer score;
public static final String SERIALIZED_NAME_BOOK_ID = "bookId";
@SerializedName(SERIALIZED_NAME_BOOK_ID)
@javax.annotation.Nonnull
private UUID bookId;
public Review() {
}
public Review id(@javax.annotation.Nullable UUID id) {
this.id = id;
return this;
}
/**
* The id of the review
* @return id
*/
@javax.annotation.Nullable
public UUID getId() {
return id;
}
public void setId(@javax.annotation.Nullable UUID id) {
this.id = id;
}
public Review title(@javax.annotation.Nonnull String title) {
this.title = title;
return this;
}
/**
* title of the review
* @return title
*/
@javax.annotation.Nonnull
public String getTitle() {
return title;
}
public void setTitle(@javax.annotation.Nonnull String title) {
this.title = title;
}
public Review content(@javax.annotation.Nonnull String content) {
this.content = content;
return this;
}
/**
* content of the review
* @return content
*/
@javax.annotation.Nonnull
public String getContent() {
return content;
}
public void setContent(@javax.annotation.Nonnull String content) {
this.content = content;
}
public Review score(@javax.annotation.Nonnull Integer score) {
this.score = score;
return this;
}
/**
* the overall score of the book
* minimum: 0
* maximum: 5
* @return score
*/
@javax.annotation.Nonnull
public Integer getScore() {
return score;
}
public void setScore(@javax.annotation.Nonnull Integer score) {
this.score = score;
}
public Review bookId(@javax.annotation.Nonnull UUID bookId) {
this.bookId = bookId;
return this;
}
/**
* reference to the book in book-service
* @return bookId
*/
@javax.annotation.Nonnull
public UUID getBookId() {
return bookId;
}
public void setBookId(@javax.annotation.Nonnull UUID bookId) {
this.bookId = bookId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Review review = (Review) o;
return Objects.equals(this.id, review.id) &&
Objects.equals(this.title, review.title) &&
Objects.equals(this.content, review.content) &&
Objects.equals(this.score, review.score) &&
Objects.equals(this.bookId, review.bookId);
}
@Override
public int hashCode() {
return Objects.hash(id, title, content, score, bookId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Review {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" content: ").append(toIndentedString(content)).append("\n");
sb.append(" score: ").append(toIndentedString(score)).append("\n");
sb.append(" bookId: ").append(toIndentedString(bookId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet openapiFields;
public static HashSet openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet();
openapiFields.add("id");
openapiFields.add("title");
openapiFields.add("content");
openapiFields.add("score");
openapiFields.add("bookId");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet();
openapiRequiredFields.add("title");
openapiRequiredFields.add("content");
openapiRequiredFields.add("score");
openapiRequiredFields.add("bookId");
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Review
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Review.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Review is not found in the empty JSON string", Review.openapiRequiredFields.toString()));
}
}
Set entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry entry : entries) {
if (!Review.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Review` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Review.openapiRequiredFields) {
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("id") != null && !jsonObj.get("id").isJsonNull()) && !jsonObj.get("id").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("id").toString()));
}
if (!jsonObj.get("title").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `title` to be a primitive type in the JSON string but got `%s`", jsonObj.get("title").toString()));
}
if (!jsonObj.get("content").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `content` to be a primitive type in the JSON string but got `%s`", jsonObj.get("content").toString()));
}
if (!jsonObj.get("bookId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `bookId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bookId").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public TypeAdapter create(Gson gson, TypeToken type) {
if (!Review.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Review' and its subtypes
}
final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Review.class));
return (TypeAdapter) new TypeAdapter() {
@Override
public void write(JsonWriter out, Review value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Review read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Review given an JSON string
*
* @param jsonString JSON string
* @return An instance of Review
* @throws IOException if the JSON string is invalid with respect to Review
*/
public static Review fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Review.class);
}
/**
* Convert an instance of Review to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
Какой правильный способ генерировать только классы модели Java, которые включают аннотации валидации Lombok и Javax с использованием openapi-generator-cli?
Я пытаюсь генерировать модели Java Pojo из файла openapi 3.0 yaml с использованием openapi-generator-cli. Требования к ключам:
Модели должны использовать аннотации Lombok (например, @date , @builder и т. Д.) @Size и т. Д.)[code]openapi: 3.0.1 info: title: ReviewApis version: 1.0.0 description: API for managing book reviews
components: schemas: Review: type: object required: [title, content, score, bookId] properties: id: type: string format: uuid title: type: string minLength: 10 maxLength: 100 content: type: string minLength: 100 maxLength: 500 score: type: integer minimum: 0 maximum: 5 bookId: type: string format: uuid < /code> Вот команда, которую я использовал: < /p> openapi-generator-cli generate \ -i ./review-service.yaml \ -o review-models \ -g java \ --enable-post-process-file \ --type-mappings DateTime=java.time.OffsetDateTime,Date=java.time.LocalDate \ --import-mappings DateTime=java.time.OffsetDateTime,Date=java.time.LocalDate \ --additional-properties lombok=true,useBeanValidation=true,dateLibrary=java8,interfaceOnly=true \ --skip-validate-spec < /code> Но сгенерированные модели не включают аннотации Lombok или аннотации проверки бобов. Вот класс, который я сгенерировал этой командой, однако он не имеет ни аннотаций Lombok, ни аннотации проверки находятся в полях: < /p> /* * ReviewApis * API for managing book reviews * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */
/** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); }
public static HashSet openapiFields; public static HashSet openapiRequiredFields;
static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); openapiFields.add("id"); openapiFields.add("title"); openapiFields.add("content"); openapiFields.add("score"); openapiFields.add("bookId");
// a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); openapiRequiredFields.add("title"); openapiRequiredFields.add("content"); openapiRequiredFields.add("score"); openapiRequiredFields.add("bookId"); }
/** * Validates the JSON Element and throws an exception if issues found * * @param jsonElement JSON Element * @throws IOException if the JSON Element is invalid with respect to Review */ public static void validateJsonElement(JsonElement jsonElement) throws IOException { if (jsonElement == null) { if (!Review.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null throw new IllegalArgumentException(String.format("The required field(s) %s in Review is not found in the empty JSON string", Review.openapiRequiredFields.toString())); } }
Set entries = jsonElement.getAsJsonObject().entrySet(); // check to see if the JSON string contains additional fields for (Map.Entry entry : entries) { if (!Review.openapiFields.contains(entry.getKey())) { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Review` properties. JSON: %s", entry.getKey(), jsonElement.toString())); } }
// check to make sure all required properties/fields are present in the JSON string for (String requiredField : Review.openapiRequiredFields) { if (jsonElement.getAsJsonObject().get(requiredField) == null) { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); } } JsonObject jsonObj = jsonElement.getAsJsonObject(); if ((jsonObj.get("id") != null && !jsonObj.get("id").isJsonNull()) && !jsonObj.get("id").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("id").toString())); } if (!jsonObj.get("title").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `title` to be a primitive type in the JSON string but got `%s`", jsonObj.get("title").toString())); } if (!jsonObj.get("content").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `content` to be a primitive type in the JSON string but got `%s`", jsonObj.get("content").toString())); } if (!jsonObj.get("bookId").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `bookId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bookId").toString())); } }
public static class CustomTypeAdapterFactory implements TypeAdapterFactory { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { if (!Review.class.isAssignableFrom(type.getRawType())) { return null; // this class only serializes 'Review' and its subtypes } final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); final TypeAdapter thisAdapter = gson.getDelegateAdapter(this, TypeToken.get(Review.class));
/** * Create an instance of Review given an JSON string * * @param jsonString JSON string * @return An instance of Review * @throws IOException if the JSON string is invalid with respect to Review */ public static Review fromJson(String jsonString) throws IOException { return JSON.getGson().fromJson(jsonString, Review.class); }
/** * Convert an instance of Review to an JSON string * * @return JSON string */ public String toJson() { return JSON.getGson().toJson(this); } } [/code] Какой правильный способ генерировать только классы модели Java, которые включают аннотации валидации Lombok и Javax с использованием openapi-generator-cli?
Я использую OpenAPI-Generator-maven-plugin , чтобы генерировать Failign Clients and Models из Spec.openapi: 3.0.1
info:
title: ReviewApis
version: 1.0.0
paths:
/create-new-review:
post:
summary: Create a new review
operationId: createNewReview
......
Я использую OpenAPI-Generator-maven-plugin , чтобы генерировать Failign Clients and Models из Spec.openapi: 3.0.1
info:
title: ReviewApis
version: 1.0.0
paths:
/create-new-review:
post:
summary: Create a new review
operationId: createNewReview
......
Я работаю над проектом весенней загрузки с уже реализованной интеграцией Kafka (производитель сообщений Kafka). Конфигурация kafka выполняется в application.properties следующим образом:
Использование OpenAPI-Generator-Maven-Plugin 7.9.0 в проекте Spring Boot 3.3.4. Вот мой пример спецификации:
/scripts/search:
post:
operationId: getScriptByFilter
requestBody:
description: JSON Request Data
content:
application/json:
schema:...
Я использую openapi-generator-gradle-plugin:4.3.0 для создания API и моделей из файла openApi-generate.yaml. Я установил SkipDefaultInterface: true в configOptions, реализация интерфейсов по умолчанию не генерируется и ApiUtil.java нигде не...