This guide provides practical guidance for customizing OpenAPI Generator templates to match your project’s needs.
Create the directory structure for your customizations:
src/main/resources/
└── template-customizations/
└── spring/ # Generator-specific directory
├── pojo.mustache.yaml # Model class customizations
├── model.mustache.yaml # Model wrapper customizations
└── enumClass.mustache.yaml # Enum class customizations
Start with a simple insertion:
# src/main/resources/template-customizations/spring/pojo.mustache.yaml
metadata:
name: "Enhanced Model Template"
description: "Adds custom header and validation imports"
insertions:
- before: ""
content: |
/**
* Generated model class
* Created:
*/
- after: ""
content: |
import jakarta.validation.constraints.*;
conditions:
templateNotContains: "import jakarta.validation.constraints.*;"
Enable template customizations in your build configuration:
openapiModelgen {
defaults {
userTemplateCustomizationsDir "src/main/resources/template-customizations"
}
specs {
api {
inputSpec "src/main/resources/openapi/api.yaml"
modelPackage "com.example.model"
}
}
}
./gradlew generateApi
Check the generated code in build/generated/sources/openapi/src/main/java/ to see your customizations applied.
Add imports conditionally to avoid duplicates:
insertions:
- after: ""
content: |
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
conditions:
templateNotContains: "import com.fasterxml.jackson.annotation.JsonInclude;"
- after: ""
content: |
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
conditions:
templateNotContains: "import jakarta.validation.Valid;"
insertions:
- after: ""
content: |
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
conditions:
templateContains: ""
insertions:
- after: "public class "
content: |
/**
* Audit fields
*/
@JsonIgnore
private Instant createdAt;
@JsonIgnore
private Instant updatedAt;
insertions:
- after: ""
content: |
/**
* Custom validation method
*/
public boolean isValid() {
// Add your validation logic here
return true;
}
/**
* Audit timestamp setter
*/
public void touch() {
this.updatedAt = Instant.now();
if (this.createdAt == null) {
this.createdAt = Instant.now();
}
}
Apply customizations based on conditions:
insertions:
- after: ""
content: |
@java.io.Serial
conditions:
generatorVersion: ">=7.11.0" # Only for newer versions
- before: ""
content: |
@Deprecated
@SuppressWarnings("removal")
conditions:
templateContains: ""
Use nested template variables for dynamic content:
openapiModelgen {
defaults {
templateVariables([
companyName: "Acme Corporation",
currentYear: "2025",
copyright: "Copyright © ",
customHeader: "\\nGenerated by OpenAPI Model Generator"
])
}
}
insertions:
- before: ""
content: |
/**
*
*
* Model:
* Package:
*/
Apply multiple customizations to the same template:
insertions:
# Add custom header
- at: "start"
content: |
/*
*
* This file was generated automatically. Do not edit.
*/
# Add custom imports after Jackson
- after: ""
content: |
import com.company.validation.CustomValidator;
# Add custom field before class definition ends
- before: ""
content: |
@JsonIgnore
private CustomValidator validator = new CustomValidator();
# Add custom method at end
- at: "end"
content: |
/**
* Custom validation using company validator
*/
public boolean validate() {
return validator.isValid(this);
}
Replace existing content instead of just inserting:
replacements:
# Replace default @Generated annotation
- pattern: "@Generated(value = \"org.openapitools.codegen.languages.SpringCodegen\""
replacement: "@Generated(value = \"com.company.openapi.generator\", date = \"\""
# Enhance toString method
- pattern: "public String toString() {"
replacement: |
/**
* Enhanced toString with null safety
*/
@Override
public String toString() {
Add template library dependencies:
dependencies {
openapiCustomizations 'com.company:api-templates:2.1.0'
openapiCustomizations 'com.company:validation-templates:1.0.0'
}
openapiModelgen {
defaults {
useLibraryTemplates true
useLibraryCustomizations true
templatePrecedence([
'user-templates',
'user-customizations',
'library-templates',
'library-customizations',
'plugin-customizations',
'openapi-generator'
])
}
}
my-templates-lib/
├── src/main/resources/
│ ├── META-INF/
│ │ ├── openapi-library.yaml # Library metadata
│ │ ├── openapi-templates/ # Explicit templates
│ │ │ └── spring/
│ │ │ └── customModel.mustache
│ │ └── openapi-customizations/ # YAML customizations
│ │ └── spring/
│ │ ├── pojo.mustache.yaml
│ │ └── model.mustache.yaml
│ └── build.gradle
# src/main/resources/META-INF/openapi-library.yaml
name: "company-api-templates"
version: "2.1.0"
description: "Company standard API templates with validation and audit support"
author: "Platform Team"
homepage: "https://github.com/company/api-templates"
supportedGenerators:
- "spring"
- "java"
minOpenApiGeneratorVersion: "7.11.0"
minPluginVersion: "1.2.0"
features:
customValidation: true
lombokSupport: true
auditFields: true
springBootIntegration: "3.x"
// my-templates-lib/build.gradle
plugins {
id 'java-library'
id 'maven-publish'
}
publishing {
publications {
maven(MavenPublication) {
from components.java
}
}
}
openapiModelgen {
defaults {
// No logging configuration needed - rich debug log always captured
}
}
# View complete debug log (always available)
cat build/logs/openapi-modelgen-debug.log
# Filter for template customization entries
grep -i "customization" build/logs/openapi-modelgen-debug.log
# Use standard Gradle flags for console output
./gradlew generateApi --info
INFO: Processing template customizations from: src/main/resources/template-customizations/spring
DEBUG: Template 'pojo.mustache' resolved from: user-customizations
DEBUG: Applied 3 insertions and 1 replacement to pojo.mustache
DEBUG: Template 'model.mustache' resolved from: openapi-generator (no customizations)
Check the working directory to see processed templates:
build/template-work/spring-{specName}/ # Each spec has its own directory
├── .working-dir-cache # Cache metadata
├── pojo.mustache # Processed template with customizations
├── model.mustache # Base template (no customizations)
└── enumClass.mustache # Base template (no customizations)
Symptoms:
Causes & Solutions:
❌ Problem: You have both explicit template AND YAML customizations
src/main/resources/openapi-templates/spring/pojo.mustache
src/main/resources/template-customizations/spring/pojo.mustache.yaml
✅ Solution: Remove explicit template to allow YAML customizations
❌ Problem: Templates in wrong directory
src/main/resources/template-customizations/pojo.mustache.yaml
✅ Solution: Use generator-specific directory
src/main/resources/template-customizations/spring/pojo.mustache.yaml
✅ Solution: Check base template for correct pattern insertions:
Symptoms:
Common YAML Issues:
❌ Incorrect indentation
insertions:
- after: "pattern"
content: |
Some content
✅ Correct indentation
insertions:
- after: "pattern"
content: |
Some content
❌ Missing quotes in conditions
conditions:
templateContains:
✅ Proper quoting
conditions:
templateContains: ""
Problem: Generated code has incorrect indentation
Solutions:
# Use explicit indentation indicators
insertions:
- after: ""
content: |2
@java.io.Serial # Preserves exactly 2 spaces
# Use quoted strings for precise control
insertions:
- after: ""
content: " @java.io.Serial\n" # Exactly 4 spaces + newline
# Use folded scalars for long text
insertions:
- before: ""
content: >
This long comment will be folded into a single line
but paragraph structure is preserved.
❌ Broad pattern (slower)
insertions:
Group related customizations in single files rather than multiple files
spring/, java/, etc.)validation.mustache.yaml, audit-fields.mustache.yaml)This guide covers the most common template customization scenarios. For the complete technical reference, see the Template Schema Reference.